我正在尝试创建自定义 UITableViewCell。第一次完美运行,但是当我重新加载数据时,旧单元格不会被删除,而新单元格会出现在它们上面。 这是代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *TableViewCellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:TableViewCellIdentifier];
}
Contact * cellContact = [contactsList objectAtIndex:indexPath.row];
[cell.contentView addSubview:[self createViewForCellWithContact:cellContact]];
return cell;
这有什么问题吗?
最佳答案
static NSString *TableViewCellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
您正在为所有行使用带有标识符“Cell”的 dequeueReusableCellWithIdentifier,这意味着将创建单个单元格并将其用于每一行。
执行此操作的正确方法是创建自定义 UiTableViewCell 类,并通过仅更改内容来重用它。
因为您没有提供所显示的 tableviewcell 的详细信息。 这里有一些简单的方法可以解决这个问题
1) 不是重复使用相同的单元格,而是为每一行创建新的单元格 (但这会占用大量内存,因为我们不是重复使用单个单元格,而是为每一行创建单元格)
UITableViewCell *cell = [[UITableViewCell alloc]init];
2) 删除单元格的 subview 并再次添加
在您的 createViewForCellWithContact 方法中,将标记添加到您要返回的 View 中,并在 cellForRowAtIndexPath 方法中 在添加另一个 subview 之前从单元格中删除 View
UIView *removeView= [cell viewWithTag:1];
[removeView removeFromSuperview];
关于ios - UITableViewCell 未被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109681/