storyboard搭建项目_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设置为“任务列表” :

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值