在UITableView 初始化的时候,可以选择要显示什么样式的表格,它的 style 参数是个枚举类型,可以自行选择要显示的样式。Group型是分组显示,Plain是一般列表型。
1. 数据展示的条件
- UITableView 的所有数据都是由数据源(dataSource)来提供,所以要想再UITableView中展示数据,必须先设置UITableView 的dataSource数据源对象。
- 要想作为UITableView的dataSource对象,它必须遵守UITableViewDataSource协议,然后实现相应的数据源方法,才能使数据显示在 UITableView 中。
- 当UITableView想要展示数据的时候,就会给数据源发送消息(即调用数据源的相应方法),UITableView 会根据方法返回值来决定显示什么数据。
2. 数据展示的过程
1)先调用数据源中的以下方法来得知要显示多少组数据:
- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
2)调用数据源的以下方法来获知第section组中一共有多少行:
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
3)调用数据源的以下方法来获知第 indexPath.section 组中的第 indexPath.row 行要显示怎样的cell(即什么内容)
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
3. 常见数据源及代理方法
1)一共多少组:
- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
2)第section组中一共有多少行:
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
3)第 indexPath.section 组中的第 indexPath.row 行要显示怎样的cell(即什么内容)
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
4)第section组要显示怎样的头部标题
- (NSString *)tableView: (UITableView *)tableView titleForHeaderInSection: (NSInteger)section;
5)第section组要显示怎样的尾部信息(一般是解释性信息)
- (NSString *)tableView: (UITableView *)tableView titleForFooterInSection: (NSInteger)section;
6) 返回表格右边的索引条,用以快速寻找某项数据,它的顺序是根据表格中的数据组的顺序来一一对应
- (NSArray *)sectionIndexTitlesForTableView: (UITableView *)tableView
7) 监听列表项点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
4. 数据刷新
//这个方法一般用以刷新列表中大量的数据
// [_tableView reloadData];
// 这一方法用以刷新少量目标行
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
[_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
5. 数据加载优化
#pragma mark 返回每一行的cell
#pragma mark 每当有一个cell进入视野范围内就会调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"C1";
// 1.从缓存池中取出可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.如果缓存池中没有可循环利用的cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
cell.textLabel.text = [NSString stringWithFormat:@"第%d行数据", indexPath.row];
return cell;
}