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

Rya*_*zel 2 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;
}
Run Code Online (Sandbox Code Playgroud)

Mox*_*oxy 5

我发现引起它的那条线!

((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
Run Code Online (Sandbox Code Playgroud)

你通过发送获取标签-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;
}
Run Code Online (Sandbox Code Playgroud)