Hands-On Full:Stack Development with Swift
上QQ阅读APP看书,第一时间看更新

Adding items to the list

To add items, we will need to add a new bar button to our navigation bar and set up a tap handler on the button so that we can respond to it by showing an input dialog to the user to enter the name of the item they want to add. To do so, we need to perform the following steps:

  1. Open up our Main.storyboard, search for Bar Button Item from the Object library, and drag it to the right-hand side of the navigation bar:
  1. Select the Bar Button Item and change the System Item to Add:
  1. Click the Assistant Editor to open the source code for our Table View Controller side-by-side with the storyboard:
  1. Control click on the add button (+) and drag into into your source code file where there is a blank line outside of any method and leave it:
  1. You will then see a modal where you need to change the Connection to Action and Type to UIBarButtonItem. In the Name field, give your method a name. I called mine didSelectAdd:

This will add a method to your controller with the following signature:

 @IBAction func didSelectAdd(_ sender: UIBarButtonItem)
  1. Inside of this method, we need to add the following code to create an alert dialog, present it, ask the user for the input, handle the input by creating a new Item, append the new item to our items array, and then refresh the table view to show the new item:
let alert = UIAlertController(title: "New shopping list item",
message: "Enter item to add to the shopping list:",
preferredStyle: .alert)

alert.addTextField(configurationHandler: nil)

alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (_) in
if let itemName = alert.textFields?[0].text {
let itemCount = self.items.count;
let item = Item(name: itemName)
self.items.append(item)
self.tableView.insertRows(at: [IndexPath(row: itemCount, section: 0)], with: .top)
}
}))

self.present(alert, animated: true, completion: nil)
  1. Let's run this to see how it looks:

Great! Now we are able to add an item to our app. Let's look at how to edit it.