UITableViewCell未删除

时间:2015-05-07 19:08:31

标签: ios uitableview

我正在尝试创建自定义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;

}

这有什么问题?

3 个答案:

答案 0 :(得分:1)

每次调用该方法时,都会将子视图添加到单元格的内容视图中。这就是为什么在单元格中有越来越多的视图,看起来好像它们在彼此之上!

createViewForCellWithContact会发生什么?

答案 1 :(得分:1)

static NSString *TableViewCellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];

您正在为所有行使用带有标识符“Cell”的dequeueReusableCellWithIdentifier,这意味着将创建一个单元格并用于每一行。

正确的方法是创建一个自定义的UiTableViewCell类,并通过更改内容来重用它。

因为您没有提供您正在展示的tableviewcell的详细信息。 这里有一些解决问题的简单方法

1)而不是重复使用相同的单元格为每一行创建新的单元格 (但这需要大量内存,因为我们不是重复使用单个单元格,而是为每一行创建单元格)

UITableViewCell *cell = [[UITableViewCell alloc]init];

2)删除单元格的子视图并重新添加

在createViewForCellWithContact方法中,向要返回的视图添加标记,并在cellForRowAtIndexPath方法中添加标记 在添加另一个子视图之前从单元格中删除视图

UIView *removeView= [cell viewWithTag:1];
[removeView removeFromSuperview];

答案 2 :(得分:0)

如果您正在尝试制作自定义UITableViewCell,则无需以编程方式将自定义单元格添加到UITableViewCell的视图中。相反,您应该只是初始化自定义单元格并将其返回。

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath)indexPath){
    static NSString *identifier = @"cell"
    Contact *cell = [tableView dequeReusableCellWithIndentifier:identifier];
    if(cell==nil)
        cell = [Contact alloc]initWithStyle:UITableViewCellStyleDefault
              reuseIdentifier:TableViewCellIdentifier];
   //Do thing specific to this cell, set custom variables

    return cell;
}