- Hands-On Full:Stack Development with Swift
- Ankur Patel
- 345字
- 2021-08-27 19:39:47
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:
- 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:

- Select the Bar Button Item and change the System Item to Add:

- Click the Assistant Editor to open the source code for our Table View Controller side-by-side with the storyboard:

- 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:

- 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)
- 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)
- 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.
推薦閱讀
- Modern JavaScript Web Development Cookbook
- 物聯(lián)網(wǎng)識別技術
- Hands-On Industrial Internet of Things
- 網(wǎng)絡故障現(xiàn)場處理實踐(第4版)
- 社交電商運營策略、技巧與實操
- OpenLayers Cookbook
- 物聯(lián)網(wǎng)關鍵技術及應用
- HCNA網(wǎng)絡技術
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- 6G新技術 新網(wǎng)絡 新通信
- React Cookbook
- 移動物聯(lián)網(wǎng):商業(yè)模式+案例分析+應用實戰(zhàn)
- 物聯(lián)網(wǎng)與智慧農(nóng)業(yè)
- NB-IoT原理和優(yōu)化
- 算力網(wǎng)絡:云網(wǎng)融合2.0時代的網(wǎng)絡架構與關鍵技術