Learning Swift by Robin Nixon

Learning Swift by Robin Nixon

Author:Robin Nixon
Language: eng
Format: epub
Publisher: O'Reilly Media, Inc.
Published: 2017-03-27T04:00:00+00:00


that are not url. We use the original URL because if urlForModifying is different

from the original url variable, we may not actually remove the entry from the list.

Lastly, we update the list of files by calling the collection view’s reloadData method.

Run the app, and tap the Edit button. The delete buttons will appear, and you can tap

them to delete them.

Renaming Documents

Finally, we’ll add the ability to rename documents when you tap their labels. The code

for this will work in a similar way to deleting them: we’ll give each cell a closure to

run when the user taps the label; and in this closure, we’ll present a box that lets the

user enter a new name.

To detect taps on the label, we need to create a gesture recognizer and connect it. We’ll

be using a very simple “tap” gesture recognizer in this chapter, but we’ll be using a

more complex one later, in “Deleting Attachments” on page 310:

1. Open Main.storyboard, and locate the label in the collection view cell.

2. Select the label, and go to the Attributes Inspector. Scroll down to the View sec‐

tion in the inspector, and select the User Interaction Enabled checkbox. This will

allow the label to respond to taps.

Let’s now add the ability to detect when the user has tapped the label:

1. Add the following code to the collectionView(_, cellForItemAt: indexPath)

method, after the deletion code:

override func collectionView(_ collectionView: UICollectionView,

cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

// Get our cell

let cell = collectionView

.dequeueReusableCell(withReuseIdentifier: "FileCell",

for: indexPath) as! FileCollectionViewCell

// Get this object from the list of known files

let url = availableFiles[indexPath.row]

// Get the display name

var fileName : AnyObject?

do {

try (url as NSURL).getResourceValue(&fileName,

forKey: URLResourceKey.nameKey)

if let fileName = fileName as? String {

cell.fileNameLabel!.text = fileName

Renaming Documents | 247

}

} catch {

cell.fileNameLabel!.text = "Loading..."

}

cell.setEditing(self.isEditing, animated: false)

cell.deletionHander = {

self.deleteDocumentAtURL(url)

}

> let labelTapRecognizer = UITapGestureRecognizer(target:cell,

> action: #selector(FileCollectionViewCell.renameTapped))))

>

> cell.fileNameLabel?.gestureRecognizers = [labelTapRecognizer]

>

> cell.renameHander = {

> self.renameDocumentAtURL(url)

> }

// If this cell is openable, make it fully visible, and

// make the cell able to be touched

if itemIsOpenable(url) {

cell.alpha = 1.0

cell.isUserInteractionEnabled = true

} else {

// But if it's not, make it semitransparent, and

// make the cell not respond to input

cell.alpha = 0.5

cell.isUserInteractionEnabled = false

}

return cell

}

This code does several things:

• First, it removes any existing gesture recognizers from the label. This is neces‐

sary because cells get reused; if we don’t remove existing recognizers, we’ll end

up with labels that attempt to rename multiple files at once when they’re

tapped.

• Next, it creates a new UITapGestureRecognizer and makes it call the cell’s

renameTapped method. It then adds it to the label. Once this is done, tapping

the label will make the cell call the rename handler block, which is added next.

The rename block simply calls the renameDocumentAtURL method, which you’ll

add in a second.

2. Add the following method to DocumentListViewController:

248 | Chapter 8: Working with Files in iCloud

func renameDocumentAtURL(_ url: URL) {

// Create an alert box

let renameBox = UIAlertController(title: "Rename Document",

message: nil, preferredStyle: .alert)

// Add a text field to it that contains its current name, sans ".note"

renameBox.addTextField(configurationHandler: { (textField) -> Void in

let filename = url.lastPathComponent

.replacingOccurrences(of: ".note", with: "")

textField.text = filename

})

// Add the cancel button, which does nothing

renameBox.addAction(UIAlertAction(title: "Cancel",

style: .



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(207858)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(176251)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(84674)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(84309)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(84099)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74440)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50894)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40262)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40216)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40096)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32733)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32509)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32454)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32388)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32361)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32333)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32259)
What's Done in Darkness by Kayla Perrin(27150)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26523)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26459)