UITableViewController中静态cell与动态c
2021-11-30 本文已影响0人
芮淼一线
太久没用,记录一下
场景
tableview中有2个section,
第一个section中的cell时静态配置
第二个section中的cell动态生成
代码
- (void)viewDidLoad {
[super viewDidLoad];
//必须注册cell
[self.tableView registerClass:TableViewCell.class forCellReuseIdentifier:@"TableViewCell"];
}
#pragma mark --重点注意:有动态cell时,高度也要重写
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1) {
return 44;
}
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
return cell;
}
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
//当覆盖storyboard中的staticcell时,因为数据源对新加进来cell的层级一无所知,所以需要写这个代理方法。否则会导致崩溃
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 1) {
return [super tableView:tableView indentationLevelForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
}
return [super tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
}
注意事项
- Storyboard中设置动态section时必须有一个用于占位的cell,这个cell可以设置Identifier(也可以不设置)
- 必须手动注册cell,不能直接使用dequeueReusableCellWithIdentifier:方法获取Storyboard中动态section中通过Identifier注册的cell(普通tableView可以这样使用)
- 必须实现动态cell的高度
- 必须实现tableView:indentationLevelForRowAtIndexPath:协议
总之上面的4点必须注意,否则就会Carsh