表视图中的重复行

时间:2011-11-10 12:11:32

标签: ios uitableview uilabel

我知道有类似的问题,但它们对我不起作用!

我的行重复,当用户返回任何带有表格视图的标签时,UILabel的文本会变得更大胆。

这是cellForRowAtIndexPath的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
CustomCell *cell = (CustomCell *)
[tableView dequeueReusableCellWithIdentifier:CellClassName];

if (cell == nil) 
{
    NSArray *topLevelItems = [cellLoader instantiateWithOwner:self options:nil];
    cell = [topLevelItems objectAtIndex:0];
}

cell.subnavName.text = [array objectAtIndex:[indexPath section]];

UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"subnavigation_off.png"]];

[cell setBackgroundView:background];

background = [[UIImageView alloc] 
              initWithImage:[UIImage imageNamed:@"subnavigation_on.png"]];

cell.selectedBackgroundView = background;
[background release];

return cell;

} 当用户从另一个选项卡返回此选项卡时,我该怎么做才能避免UILabel上的文本再次添加到我的单元格中?我读了一些关于使用标签的内容,但我找不到办法。

非常感谢!

1 个答案:

答案 0 :(得分:1)

Soooooo经典错误。

问题(这里总是关于TableView问题)是你没有正确使用TableViewCells的重用机制。

你应该尝试出列(回收)现有的单元格,如果它没有返回一个单元格(tableview没有设法回收旧的 - 已经分配但不再使用的单元格),那么分配它并配置所有单元格共有的每个属性(标签字体,添加子视图,更改颜色等)。

然后,在“if”之外 - 因此,无论细胞是新分配的细胞还是已经回收的细胞(来自先前分配但不再使用的细胞),在所有情况下 - 填充细胞取决于indexPath(文本,图像等)的具体内容

阅读Apple文档中的Table View编程指南,并在StackOverflow上搜索有很多关于TableView的问题都存在同样的问题。