创建一个Table View
注意一切一UI前缀开头的,这些都是UIKit包括的内容。
//From:ViewControlle.swift
class ChecklistViewController: UITableViewController{
}
然后更改ViewController
的名字为ChecklistViewController
回到Storyboard
,从右边栏的show object library
选项中拖过来一个TableViewController

然后点击Xcode
右侧的Identity inspector
,在 Custom Class
中输入ChecklistViewController

此时的outline pane
显示的标题将会变成Checklist View Controller Scene
,如果你的Storyboard上没有TableView Prototype Content
字样,到右侧的Attributes inspector
中查看View Controller
一栏的Is initial View Controller
选项,然后勾选。完成勾选后,这一页将会是用户看到的首页;没有这一选项,IOS将不回知道应该首先展示给用户那一页。(PS:如果你运行 APP 时,显式的是黑色的,请首先查看自己是否选择了Is initial View Controller
)
到此时,你可以打开IOS模拟器,将会显示一个空的List页面。

这个效果是基于UIViewTable来实现的,这里有两种类型的表单plain
和 grouped
。

然后打开storyboard
,选中Prototype Cells

然后拖拽一个Label到Prototype Cells

重新选中Table View Cell
,然后到Attributes inspectors
,设置accessory
为 checkmark
,其实就是给Label后面添加一个对号的图标


接下来设置一个 reuse identifier
这个的主要作用是为了系统可以判断什么时候新的被滚动上来的单元格覆盖到被标记的单元格,以此来实现单元格的重新使用,提高系统的运行效率。
选中 Table View Cell
点击 Attributes inspector
添加Identifier
为 ChecklistItem
。

接下来在ChecklistViewController.swift
的最下面的花括号前添加下列代码。
//返回有多少行数据
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 }
//将数据内容赋值在 cell 上
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath)
return cell
}
这是两个被重写属于UITableView
的构造函数,这两个方法是用来连接数据和UI 界面的。首先Table View
会调用带有numberOfRowsInSection
的方法,来查询有多少条数据。当要将内容显示在Cell
上时,会调用带有 cellForRowAt
的方法,将数据赋值在Cell
上。
为单元格添加数据
在 storyboard
上选中Label
点击 Attrbutes inspector
然后在 Tag
标签上将数值改为 1000 。(你要确定选中的是 Label,而不是 Content View 或者其它)

Tag
是一个数字的标识值,能够让用户界面的排序更加方便,之所以数值为1000也没有什么特殊的愿意,只是因为1000是个还不错的选择。
修改ChecklistViewController.swift 的 tleVeiw
方法,代码像下面一样。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath)
let label = cell.viewWithTag(1000) as! UILabel
if indexPath.row == 0 { label.text = "Walk the dog" } else if indexPath.row == 1 {
label.text = "Brush my teeth" } else if indexPath.row == 2 {
label.text = "Learn iOS development" } else if indexPath.row == 3 {
label.text = "Soccer practice" } else if indexPath.row == 4 {
label.text = "Eat ice cream" }
return cell
}
下面这段代码定义了一个 cell
常量,这个cell
常量是一个可以重复使用的队列单元。函数中的两个变量一个是找到身份验证的标志,另一是可以方便检索分类用途的索引。
let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath)
下面这一行代码就是你之前在故事板中设置的按个 Tag,它会返回一个跟 UIlabel 相关的引用。使用Tag 是一个无需创建@IBOutlet变量就可以得到 UI元素的简单技巧。
let label = cell.viewWithTag(1000) as! UILabel
再接下来的代码就是一系列的判断语句,这里面用到的 indexPath 和 label 对象就是上文中提到的,indexPath 可以用于检索和分类,用 indexPath.row 就可以获得到 table 中的行。label 是一个通过 cell 获取到的 UI 元素,label.text 就可以获取或者设置 label 的值啦。
那么至此,最基本的在表单上显式数据的实现流程就完成啦。
下一章: Delegate (委托)
网友评论