Todos的功能:
添加数据
更改数据
删除数据
批量删除数据
移动数据
Main.storyboard:
删除原本的ViewController 创建一个Table View Controller,并且钩上Is Initial View Controller
删除左栏的ViewController,在Cocoa Touch Class添加一个TableViewController,命名为TodosController并整理为MVC格式
Model内创建Todo结构体
import Foundation
struct Todo {
var name = ""
var checked = false
}
实例化Todo
class TableViewController: UITableViewController {
var todos = [
Todo(name: "吃大象", checked: false),
Todo(name: "开飞机", checked: false),
Todo(name: "造坦克", checked: false),
Todo(name: "坐火箭", checked: false),
Todo(name: "炸学校", checked: false)
]
设置tableview的段数和行数
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return todos.count
}
创建TableViewCell
在cell里面增加两个label
与cell连接
@IBOutlet weak var checkMark: UILabel!
@IBOutlet weak var Todo: UILabel!
更改cell的Accessory属性
将todos里面的Todo依次放入cell中:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "todo", for: indexPath) as! TodoCell
cell.checkMark.text = todos[indexPath.row].checked ? "√" : ""
cell.todo.text = todos[indexPath.row].name
// Configure the cell...
return cell
}
效果:
添加点击后打勾与取消打勾效果
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//更改数据
todos[indexPath.row].checked = !todos[indexPath.row].checked
//更新视图
let cell = tableView.cellForRow(at: indexPath) as! TodoCell
cell.checkMark.text = todos[indexPath.row].checked ? "√" : ""
tableView.deselectRow(at: indexPath, animated: true)
}
实现添加功能
创建TodoController,添加一个text
用Navigation Controller连接,并添加一个bar button item,与新的controller连接
设置新的tableview controller的行数列数
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #wa