Database Reference
In-Depth Information
The second method,
tableView(_:cellForRowAtIndexPath:)
, dequeues table view
cells and populates them with the corresponding string in the
names
array.
Don't run the app just yet. First, you need a way to input names so the table view
can display them.
Implement the
addName
IBAction
method you Ctrl-dragged into your code earlier:
//Implement the addName IBAction
@IBAction
func
addName(sender:
AnyObject
) {
var
alert =
UIAlertController
(title:
"New name"
,
message:
"Add a new name"
,
preferredStyle: .
Alert
)
let
saveAction =
UIAlertAction
(title:
"Save"
,
style: .
Default
) { (action:
UIAlertAction
!) -> Void
in
let
textField = alert.
textFields
![
0
]
as
UITextField
self
.
names
.
append
(textField.
text
)
self
.
tableView
.
reloadData
()
}
let
cancelAction =
UIAlertAction
(title:
"Cancel"
,
style: .
Default
) { (action:
UIAlertAction
!) -> Void
in
}
alert.
addTextFieldWithConfigurationHandler
{
(textField:
UITextField
!) -> Void
in
}
alert.
addAction
(saveAction)
alert.
addAction
(cancelAction)
presentViewController
(alert,
animated:
true
,
completion:
nil
)
}
Every time you tap the
Add
bar button item, this method presents an
UIAlertController
with a text field and two buttons,
Save
and
Cancel
.
Save
takes whatever text is currently in the text field, inserts it into the
name
array
and reloads the table view. Since the
names
array is the model backing the table
view, whatever you typed into the text field will appear in the table view.
Finally it's time to build and run your app for the first time. Tap the
Add
bar button
item. The alert controller will look like this: