Adding new items to the checklist


3-0

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
  • 打开 添加事项 界面使用户可以输入事项

3-1

3-2

3-3

3-4

3-5

3-6

3-7

3-8

Add a new action method to ChecklistViewController.swift:

@IBAction func addItem() {
}

3-9

3-10

3-11

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 总结

  1. created a new ChecklistItem object 添加一个新的 ChecklistItem 对象
  2. added it to the data model, and 把它添加到 数据模型,并且
  3. inserted a new cell for it in the table view. 插入一个新行到 TableView。

3-12

Deleting rows


3-13

override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// 1
items.removeAtIndex(indexPath.row)
// 2
let indexPaths = [indexPath] tableView.deleteRowsAtIndexPaths(indexPaths,
}
  1. remove the item from the data model, and 从 数据模型 中删除一项,并且
  2. delete the corresponding row from the table view. 从 TableView 中删除与之相符的一行。