使用自定义子视图滚动UITableView时重复数据

时间:2013-08-22 11:35:24

标签: iphone ios ios7

之前有效,除非它已经这么长时间我忽略了一些东西。当表格首先显示一切看起来很棒但是如果我向上和向下滚动标签会得到重复的内容。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, tableView.frame.size.width, 35)];

        labelName.tag = 20;

        [cell addSubview:labelName];
    }

    ((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];

    return cell;
}

2 个答案:

答案 0 :(得分:5)

我发现引起它的那条线!

((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];

您通过向-viewWithTag:发送tableView来获取标签,但您应该询问该单元格。

另一方面,最好将子视图添加到单元格contentView

这是正确的实施方式。

-(UITableViewCell *)tableView:(UITableView *)tableView 
        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                      reuseIdentifier:CellIdentifier];

        UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, tableView.frame.size.width, 35)];

        labelName.tag = 20;

        [cell.contentView addSubview:labelName];
    }

    ((UILabel *)[cell.contentView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];

    return cell;
}

答案 1 :(得分:1)

if (cell == nil)条件

中写下此波纹线
labelName.text = [data objectAtIndex:indexPath.row];

并评论或删除此波纹线..

((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];