Adding new items to the checklist
What you’ll do in this section:
我们这一期要做什么
- Add a navigation controller
- 添加一个导航栏控制器
- Put the Add button into the navigation bar
- 把一个 添加按钮 放到导航栏上
- Add a fake item to the list when you press the Add button
- 当你点击 添加按钮 时添加一个假数据
- Delete items with swipe-to-delete
- 当 滑动删除 时删除事项
- Open the Add Item screen that lets the user type the text for the item
- 打开 添加事项 界面使用户可以输入事项
Navigation controllers
Add a new action method to ChecklistViewController.swift:
@IBAction func addItem() {
}
Let’s give addItem() something to do. Back in ChecklistViewController.swift, fill out the body of that method:
@IBAction func addItem() {
// update Model
let newRowIndex = items.count
let item = ChecklistItem()
item.text = "I am a new row"
item.checked = false
items.append(item)
// update View
let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
let indexPaths = [indexPath]
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
To recap, you 总结
- created a new ChecklistItem object 添加一个新的 ChecklistItem 对象
- added it to the data model, and 把它添加到 数据模型,并且
- inserted a new cell for it in the table view. 插入一个新行到 TableView。
Deleting rows
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// 1
items.removeAtIndex(indexPath.row)
// 2
let indexPaths = [indexPath] tableView.deleteRowsAtIndexPaths(indexPaths,
}
- remove the item from the data model, and 从 数据模型 中删除一项,并且
- delete the corresponding row from the table view. 从 TableView 中删除与之相符的一行。