UITableView的介绍以及使用
1. UITableView 的两种样式
简单样式: UITableViewStylePlain
分组样式: UITableViewStyleGrouped
UITableViewCell 的默认模式只显示一个图片和一个文本
2. 如何展示数据
1> UITableView 展示数据需要设置一个数据源
2> 需要确定 UITableView 有几组数据
3> 需要确定 UITableView 每一组都是什么数据
1 数据源方法 遵守<UITableViewDataSource> 2 // 返回组数, 默认是 1, 可以不设置 3 - (NSInteger)numberOfSectionsinTableView:(UITableView *)tableView; 4 // 返回对应 section 组的行数, 必须实现 5 - (NSInteger)tableView:(UITableView *)tableView numberOfRowInSection:(NSInteger)section; 6 // indexPath 中包含组号与行号, 该方法返回对应的 Cell, 必须实现 7 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) 8 indexPath; 9 10 Section 是组号 11 Row 是行号
3.创建Cell 可以使用指定的样式:
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
};
4.设置组标题与组描述:
1 //设置头部标题 2 - (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; 3 //设置底部标题 4 - (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section; 5 //设置没行Cell的宽高 6 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
cell.accessoryType的系统样式:
UITableViewCellAccessoryNone,
UITableViewCellAccessoryDisclosureIndicator,
UITableViewCellAccessoryDetailDisclosureButton
UITableViewCellAccessoryCheckmark,
UITableViewCellAccessoryDetailButton
UITableViewCell的常见属性
1>imageView 图片
2>textLabel text
3>detailTextLabel 描述
contentView 内容容器 一把自定义Cell的使用添加控件到Cell上添加到这个属性上
backgroundView 接受一个UIView 当系统的颜色不能达到效果的时候 使用此方法
selectedBackgroundView 设置被选中的背景颜色
凡是在Cell里面设置的Frame 都无效.
UItableView的常见属性
rowHeight ( 代理可以设置每一行的行高 )
separatorColor 分割线的颜色
separatorStyle 分割线的样式
tableHeaderView 添加头部视图
tableFooterView 添加底部视图
tableView.estimatedRowHeight = ...; 预估行高,可以优化内存
//该方法设置索引条 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
1 //从缓存池里取出单元格 2 static NSString *cell_id = @"lol_cell_id"; 3 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id]; 4 if (cell == nil) { 5 cell = [[UITableViewCell alloc] 6 initWithStyle:UITableViewCellStyleSubtitle 7 reuseIdentifier:cell_id]; 8 }
刷新UITableView的数据:
1 //刷新全部数据 2 [self.tableView reloadData]; 3 4 //刷新指定行的数据,这个方法使用前提:模型数据的行数不变,否则会崩溃 5 //如果想精确的刷新某一行用这个方法: 6 [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationAutomatic]; 7 8 //刷新指定行的数据,行数发生变化的时候使用该方法 9 //如果想精确的删除某一行用这个方法: 10 [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop]; 11 12 //刷新数据后让表格往上推 13 [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
1 //设置右侧索引: 2 -(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView 3 4 //这个方法在用户点击完成时调用 5 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 6 //用户点击让点击背景颜色消失 7 [tableView deselectRowAtIndexPath:indexPath animated:YES]; 8 }