当我重复使用它时,如何完全清除细胞?

1 objective-c uitableview uikit ios

当我打电话给[table reloaddata];

用新数据重新绘制单元格,但是我的UILabel搞砸了,因为它们是在旧的UILabel上绘制的,所以它很乱.

    static NSString* PlaceholderCellIdentifier = @"PlaceholderCell";

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];


if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
    cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;


    cell.contentView.backgroundColor = [UIColor clearColor];
}
Run Code Online (Sandbox Code Playgroud)

是我的细胞的初始化.

我像这样添加一个UILabel

        UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)];
    [theDateLabel setBackgroundColor:[UIColor clearColor]];
    [theDateLabel setTextColor:[UIColor lightGrayColor]];
    [theDateLabel setText:[dateFormatter stringFromDate:theDate]];
    [theDateLabel setFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:15]];
    [cell addSubview:theDateLabel];
    [theDateLabel release];
Run Code Online (Sandbox Code Playgroud)

细胞中还有一些标签,同样的东西.

我想要发生的是旧标签从单元格中消失,以便它们不再可见.

rob*_*off 10

您不应该添加theDateLabel为子视图cell.您应该将其添加为子视图cell.contentView.

正如yuji所说,实现这一点的一种方法是UITableViewCell为每个自定义子视图创建一个带有属性的子类.这样,您可以轻松访问重用单元格的日期标签,以便为新行设置其文本.

另一种常见方法是使用tag每个人UIView拥有的属性.例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* PlaceholderCellIdentifier = @"PlaceholderCell";
    static const int DateLabelTag = 1;

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];   

        UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)];
        theDateLabel.tag = DateLabelTag;
        theDateLabel.backgroundColor = [UIColor clearColor];
        theDateLabel.textColor = [UIColor lightGrayColor];
        theDateLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15];
        [cell.contentView addSubview:theDateLabel];
        [theDateLabel release];
    }

    NSDate *theDate = [self dateForRowAtIndexPath:indexPath];
    UILabel *theDateLabel = [cell.contentView viewWithTag:DateLabelTag];
    theDateLabel.text = [dateFormatter stringFromDate:theDate];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)


yuj*_*uji 5

虽然Richard的解决方案可行,但如果您的单元格有任何其他子视图,它们也会被删除.此外,每次绘制单元格时分配和初始化子视图都不一定是最佳选择.

这里的标准解决方案是创建UITableViewCell具有属性的子类@dateLabel(对于其他标签,依此类推).然后,当你初始化一个单元格时,如果它还@dateLabel没有,你可以给它一个新单元格,否则你只需要设置它的文本.