免费开源的iOS开发学习平台

UITableView详解:2-数据源方法

UITableView表视图的数据源简介

在iOS开发过程中,苹果官方推荐使用MVC设计模式,视图类对象负责获取与响应用户操作,但具体的逻辑处理通常情况下是由视图对象的代理(通常为控制器对象)来完成的。对于UITableView类的对象,除了可以设置代理属性之外,还需要设置其数据源属性,因为UITableView中展示的数据是由其数据源对象提供的。在设置完UITableView的dataSource属性后,通过实现UITableViewDataSource协议中定义的数据源方法来为UITableView对象提供需要展示的数据。

在UITableView中,如何去标注每个单元格?例如,在Excel表格中,我们可以通过行号与列号来定位唯一一个单元格。在UITableView中,引入了NSIndexPath类来定位每一个单元格。在NSIndexPath类中,包含两个关键属性:section与row,分别对应每个单元格在UITableView中段号Section与行号Row。根据索引路径indexPath即可定位到唯一的一个单元格。

@interface NSIndexPath (UITableView)
@property (nonatomic, readonly) NSInteger section;
@property (nonatomic, readonly) NSInteger row;
@end

UITableViewDataSource中的常用方法

UITableViewDataSource协议中,有3个方法是最常使用的,一般情况下在初始化UITableView时都需要实现。这3个方法分别用于返回表视图的段数、每段的行数以及每个单元格的样式与展示内容。

  • (必选)返回每个段(seciton)中有多少个单元格;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
  • (必选)返回每个单元格的具体样式和显示内容;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
  • (可选)返回整个表视图有多少个段(section),如果不实现该方法,默认为1个段。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;  

UITableViewDataSource中的其它方法

除了上述3个常用方法之外,UITableViewDataSource中的其他方法功能介绍如下。

  • 设置某section上header的标题,当tableview的style是平铺时有悬浮效果,为分组时是没有悬浮效果的。
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
  • 设置每个段section上的footer的标题;
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
  • 设置表视图的索引;
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView;
  • 点击右侧索引栏时调用;
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;
  • 对单元格进行编辑(删除、添加)时调用;
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
  • 设置单元格是否可移动;
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
  • 对单元格的移动。
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;