Tableview记录不断重复和重叠

时间:2012-02-02 16:48:18

标签: iphone objective-c cocoa-touch

这是我的cellForRowAtIndexPath

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];   
if (cell == nil) {    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];    
}   
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12,11,320,40)];
    label.text = [animalArray objectAtIndex:indexPath.row];
    [cell addSubview:label];

animalArray我有以下项目,

Lion, Dog, Cat, Zebra, Donkey, Monkey... 

问题是;

1。)当我在if (cell == nil) {条件中添加标签时,我会看到重复的记录。比如L ion, Dog, Cat, Zebra,然后再向下Lion向下滚动。

2。)当我将其添加到if (cell == nil) {之外时,记录重叠,因为我滚动。

我明白这是因为单元格正在重复使用它,我每次都在创建一个Label(因此它会重叠)。我不知道如何以编程方式解决这个问题。有人可以帮助我。

编辑:

我刚刚在这里展示了1个标签。但我有多个标签要显示。还有一些UIComponants。

4 个答案:

答案 0 :(得分:2)

我在不检查语法的情况下编写此代码:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];   
if (cell == nil) {    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];   
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12,11,320,40)];
label.tag = 556;
    [cell.contentView addSubview:label]; 
}   
UILabel *cellLabel = (UILabel *)[cell.contentView viewWithTag:556];
    cellLabel.text = [animalArray objectAtIndex:indexPath.row];

答案 1 :(得分:0)

您不必为表格单元格添加标签。它已经有了cell.textLabel.text = @“some string”。 替换这部分:

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12,11,320,40)];
label.text = [animalArray objectAtIndex:indexPath.row];
[cell addSubview:label];

用这个:     cell.textLabel.text = [animalArray objectAtIndex:indexPath.row];

答案 2 :(得分:0)

最好的方法是将UITableViewCell子类化并添加所有标签。这样你需要在标题之外设置标签的文本属性 if (cell == nil){...} 块。

答案 3 :(得分:-2)

通过删除if(cell == nil)

来使用它
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];   
   cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];    
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12,11,320,40)];
label.text = [animalArray objectAtIndex:indexPath.row];
[cell addSubview:label];
[label release];