需求:在cellForRowAtIndexPath
中直接创建其他view时,因为没有使用重用机制
,为防止会创建多个view可以这样:
以下两个UIview只能同时存在一个,所以,相同的view时,不创建新的,不同的view时,需要将前一个view删掉,再创建新的下一个view
// 删掉tag为“1235”的view:
[[cell.contentView viewWithTag:1235] removeFromSuperview];
// 删掉tag为“1234”的view:
[[cell.contentView viewWithTag:1234] removeFromSuperview];
代码:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
}
cell.backgroundColor = UIColor.clearColor;
cell.contentView.backgroundColor = UIColor.clearColor;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (self.gameListDataSource.count > 0) { // 是否 > 0
GameSectionView *addGeamView = [cell.contentView viewWithTag:1234]?[cell.contentView viewWithTag:1234]:[[GameSectionView alloc]init];
addGeamView.tag = 1234;
[cell.contentView addSubview:addGeamView];
[addGeamView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(cell.contentView);
}];
// 删掉tag为“1235”的view
[[cell.contentView viewWithTag:1235] removeFromSuperview];
} else {
NotGameView *notGameHeaderView = [cell.contentView viewWithTag:1235]?[cell.contentView viewWithTag:1235]:[[NotGameView alloc] init];
notGameHeaderView.tag = 1235;
[cell.contentView addSubview:notGameHeaderView];
[notGameHeaderView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(cell.contentView);
}];
// 删掉tag为“1234”的view
[[cell.contentView viewWithTag:1234] removeFromSuperview];
}
}
网友评论