UI控件笔记之UITableView
表视图
UITableView 继承自 UIScrollView。一个表视图可以由多个分段(section)组成,每个分段可以有一个头和尾。很多情况下表视图只有一个分段,而且不显示头尾。表视图本身也可以有一个头(显示在第一个分段之前)和一个尾(显示在最后一个分段之后)。
表视图风格
UITableView 有以下两种样式(UITableViewStyle),两种风格本质无区别,只是显示样式不同而已。
- Plain(普通样式)
- Grouped(分组样式)
表视图分割线(Separator)
分割线有以下三种样式(UITableViewCellSeparatorStyle)
- None(无分割线)
- SingleLine(单线条)
- SingleLineEtched(带浮雕效果的线条)
表视图单元格(Cell)
Cell 有以下四种显示样式(UITableViewCellStyle)
- Default(左侧显示 textLabel,不显示 detailTextLabel,最左边可选显示 imageView)
- Value1(左侧显示 textLabel,右侧显示 detailTextLabel,最左边可选显示 imageView)
- Value2(左侧依次显示 textLabel、detailTextLabel,最左边可选显示 imageView)
- Subtitle(左侧上方显示 textLabel,左侧下方显示 detailTextLabel,最左边可选显示 imageView)
Cell 有以下四种选中样式(UITableViewCellSelectionStyle)
- None
- Blue
- Gray
- Default
附属图形(Accessory)
单元格的 Accessory 有以下五种样式(UITableViewCellAccessoryType)
- None(无附属图形)
- DisclosureIndicator(小箭头)
- DetailDisclosureButton(详细信息按钮 + 指向右侧的箭头)
- Checkmark(勾号)
- DetailButton(详细信息按钮)
UITableView 协议
iOS 遵循 MVC 设计模式,很多操作通过代理和外界沟通,UITableView 同理实现了以下两种协议:
- UITableViewDelegate
- UITableViewDataSource
表视图控制器(UITableViewController)
很多时候一个 UIViewController 中只有一个 UITableView,因此苹果官方为了方便大家开发直接提供了一个 UITableViewController,这个控制器实现了 UITableView 数据源和代理协议,内部定义了一个 tableView 属性供外部访问,同时自动铺满整个屏幕、自动伸缩以方便我们的开发。 如果需要用到 Table View 是不充满全屏的话,我们应该使用 UIViewController 自己创建和维护 UITableView。
从一定层面上来说,除了方便、自动设置委托和数据源属性外,表视图控制器没有任何其它的优势。
必须实现的函数
Sections数目
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 }
每个Section的Cell数目
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 100 }
注册绑定Cell ID
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(“conanIdentifier”, forIndexPath: indexPath) as! UITableViewCell //To config Cells …. }