2

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

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

2 回答 2

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;
}
于 2013-08-22T12:31:25.140 回答
1

if (cell == nil)在条件内写下下面这行

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

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

((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
于 2013-08-22T11:45:38.390 回答