官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 珲春市| 富锦市| 宁蒗| 新宁县| 孟州市| 临澧县| 阳高县| 民勤县| 渝北区| 禹州市| 西乌珠穆沁旗| 如皋市| 永年县| 正阳县| 和静县| 开平市| 通榆县| 甘孜| 祁东县| 武川县| 偃师市| 岗巴县| 政和县| 沙湾县| 长岭县| 什邡市| 苗栗市| 靖宇县| 武夷山市| 田东县| 德钦县| 寻甸| 安远县| 福建省| 靖宇县| 翼城县| 娄烦县| 乌什县| 新宾| 镇康县| 绥江县|