使用自定义子视图滚动UITableView时重复数据 [英] Duplicate data when scrolling a UITableView with custom subviews

查看:95
本文介绍了使用自定义子视图滚动UITableView时重复数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This worked before, unless it's been so long I'm overlooking something. When the table first shows everything looks great but if I scroll up and and down labels get duplicate content.

-(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;
}


推荐答案

我发现了挑起线条的行它!

I spotted the line that provokes it!

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

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

You're getting the label by sending -viewWithTag: to tableView but you should ask the cell.

在附注中,添加子视图总是更好到单元格的 contentView

On a side note it's always better to add subviews to a cell's 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;
}

这篇关于使用自定义子视图滚动UITableView时重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆