UITableView属性
tableView.rowHeight = 60;//cell的行高
Cell重用:
- 方法一
static NSString *cellName = @“cell”;
UITableViewCell *cell = [tableView dequeueReusableCellWithId:cellName];
if(cell == nil){
cell = [[UITableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
}
return cell;
- 方法二
先注册某个标识对应的cell类型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//或
[self.tableView registerNib:@"xxx" forCellReuseIdentifier:@"cell"];
然后再去缓存池找
static NSString *cellName = @"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithId:cellName];//此时会找到对应的cell
cell 设置选中后背景
cell.selectedBackgroundView = [[UIView alloc]init];
非等高的cell
加载UITableView之后,一般会先调用
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30.0f;
}
然后会调用
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
}
因此对于非等高的cell,返回高度需要先设置估计行高。
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40.0f;
}
这样的话,系统就不会按上面流程调用:先调用cellForRowAtIndexPath、再调用heightForRowAtIndexPath。最后在通过heightForRowAtIndexPath获取每一cell的高度。
//获得估计行高
(CGFloat) tableView:(UITableView) estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;
具体获取非等高cell高度
- 方法一:
在返回每行具体行高heightForRowAtIndexPath:
- 1.在获得每个cell时,先算下高度(必须调用[cell laoutIfNeed],强制布局,计算高度)。将高度存储到全局数组中
- 2.heightForRowAtIndexPath 中直接获取全局数组的对应高度。
- 方法二:
高度存储在模型中
layoutIfNeed 强制布局。
*在计算label高度时,若label用的自动布局,在同一个cell计算时每次计算结果不一样。因此可设置label一个属性。
设置label每一行文字最大宽度label.preferredMaxLayoutWidth。
添加、删除 cell
先改模型再刷新
UITableView 添加、删除 带动画
[self.tableView insertSections:(nonnull NSIndexSet *) withRowAnimation:(UITableViewRowAnimation)];
[self.tableView deleteRowsAtIndexPaths:(nonnull NSArray<NSIndexPath *> *) withRowAnimation:(UITableViewRowAnimation)];
此系列代码还具有刷新数据功能,即[self.tableView reloadData]
更新 cell
[self.tableView reloadRowsAtIndexPaths:<#(nonnull NSArray<NSIndexPath *> *)#> withRowAnimation:<#(UITableViewRowAnimation)#>]
进入编辑模式
- self.tableView.editing = YES;
- [self.tableView setEditing:YES animated:YES];
//此代理是tableView进入编辑模式后,每个cell返回的模式。
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete;
}
//编辑模式下点击编辑按钮操作代理
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
批量操作
- 方法一
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//取消选中
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//指定模型修改(修改CELL 界面显示)
...
//刷新数据
[tableView reloadData];
}
- 方法二
苹果自带的批量操作
tableView有个属性:
//允许在编辑模式下就行多选操作
self.tableView.allowsMultipleSelection = YES;
//获得所有被选中的行
NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];