当前位置: > > > Swift - 使用storyboard创建表格视图(TableViewController)

Swift - 使用storyboard创建表格视图(TableViewController)

(本文代码已升级至Swift4)

项目创建完毕后,默认是使用 ViewController 作为主界面视图。下面通过样例演示,如何使用 TableViewController 作为主界面视图,同时演示如何在 storyboard 中设置表格及内部单元格样式。

功能如下:

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
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)
    }
}
7,上述操作完毕后会发现,表格顶着最上面不好看。我们可以在头部添加一个 Navigation Controller 导航控制器。即选中 storyboard 中的主界面,然后从 XCode 的顶部菜单选择 Editor -> Embed In -> Navigation Controller

最后,选择主界面(Main Controller Scene)的 Navigation Item,将 title 设置为“任务列表” :
评论1
  • 1楼
    2016-02-27 10:56
    hard-working1

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

    站长回复

    原来写的不够清楚,是MainController的导航条设置title,我现在在文章底部也附上截图。