Swift - 使用storyboard创建表格视图(TableViewController)
(本文代码已升级至Swift4)
功能如下:
1,程序运行后即为表格页面
2,表格内容为“行号:内容”
3,点击单元格可以切换勾选与取消勾选状态
效果图如下:

详细步骤:
1,删掉 storyboard 现有的视图界面。然后从对象库中拖入一个 TableViewController 到场景中。同时将其 Attributes 面板中的 Is Initial View Controller 选中。

2,新建一个类 MainController.swift,继承自 UITableViewController

3,将场景中的 TableViewController 与新建的 MainController 进行绑定。选中主界面,然后再 Identity 面板中将 CustomClass 的 Class 属性设置为 MainController 即可。

4,选中单元格(TableViewCell),在 Attributes 面板中设置 Identifier 属性为“maincell”(供代码中使用)。
同时将 Accessory 属性设置为 Checkmark(表示单元格尾部为勾号)

5,从对象库中拖入一个 Label 控件到 cell 中,用于显示内容。同时选中这个 Label,在 Attributes 面板中设置 Tag 的值为 1000,供代码中获取标签。

6,MainController.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import UIKit class MainController : UITableViewController { var tasks:[ String ] = [ "今天任务" , "明天任务" , "后天任务" ] override func viewDidLoad() { super .viewDidLoad() } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView , numberOfRowsInSection section: Int ) -> Int { return tasks.count } override func tableView(_ tableView: UITableView , cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "maincell" , for : indexPath) //获取label let label = cell.viewWithTag(1000) as ! UILabel //设置label内容 label.text = "\(indexPath.row):\(tasks[indexPath.row])" return cell } override func tableView(_ tableView: UITableView , didSelectRowAt indexPath: IndexPath ) { //获取cell let cell = tableView.cellForRow(at: indexPath)! //根据原先状态,改变勾选或取消勾选状态 if cell.accessoryType == UITableViewCellAccessoryType .none { cell.accessoryType = UITableViewCellAccessoryType .checkmark } else { cell.accessoryType = UITableViewCellAccessoryType .none } //取消选中状态 tableView.deselectRow(at: indexPath, animated: true ) } } |


hangge, 这里【最后,选择主界面,将title设置为“任务列表” 】, 哪个主界面呢? 我直接给那个MainController的View Controller的title赋值为"任务列表"没有效果, 但我在MainController的场景导航条中设置“任务列表”或者代码在MainController中设置title都可以,为啥我第一种方法没有效果呢? 谢谢