Duplicate data when scrolling a UITableView with custom subviews

风流意气都作罢 提交于 2019-12-11 01:28:05

问题


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

回答1:


I spotted the line that provokes it!

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

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

On a side note it's always better to add subviews to a cell's contentView

Here's the right implementation.

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



回答2:


write this bellow line inside the if (cell == nil) condition

labelName.text = [data objectAtIndex:indexPath.row];

and comment or remove this bellow line..

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


来源:https://stackoverflow.com/questions/18379280/duplicate-data-when-scrolling-a-uitableview-with-custom-subviews

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!