防止 UILabel 重复添加到自定义 UITableViewCell

prevent UILabel repeat added to custom UITableViewCell

我有一个 customCell,我需要为每个单元格添加多个 UILabel 作为 "tag", 我的代码是这样的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *ID = @"topicCell";
    MSPTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    NSArray *labelArray = [TopicLabelArr objectAt:index.row];
    for (int i = 0; i < [labelArray count]; i++) {
        UILabel *tmpLabel = [UILabel alloc]initwithFrame .....];
        tmpLabel.text = [labelArray objectAt:i];
        [cell.view addSubview:tmpLabel];
    }
    return cell;
}

我使用 Xib 创建自定义单元格。 我需要的是让 for 循环在每个单元格上只执行一次。 但是tableView的行数很多,每次上下滚动都会重复创建标签。如何改进?任何的想法?谢谢

当您使用 dequeueReusableCellWithIdentifier 时,您并没有创建新的 MSPTopicCell 您(正如方法名称所说)重复使用了一个单元格。

这是什么意思?显然,您至少需要与同时显示的数量一样多的单元格,但是一旦开始滚动,滚动视图中消失的单元格将被重新使用。

您添加到子视图的标签会超时添加,即使在已经添加了一些子视图的重用单元格上,也会产生您的问题。

有很多方法可以修复它,这里有一些例子:

  • 您可以在添加新子视图之前删除添加的子视图。使用以下代码在 for 循环之前添加以下行:

    view.subviews.forEach({ [=10=].removeFromSuperview() }
    
  • 为您的标签使用自定义标签,这样您就可以看到它们是否已经存在:

    for (int i = 0; i < [labelArray count]; i++) {
        UILabel *tmpLabel = (UILabel *)[self viewWithTag:100+i];
        if (tmpLabel == nil) 
        {
            tmpLabel = [UILabel alloc]initwithFrame .....];
            tmpLabel.tag = 100 + i;
            [cell.view addSubview:tmpLabel];
        }
        tmpLabel.text = [labelArray objectAt:i];
    }
    
  • 最佳解决方案,在我看来,因为您已经使用了 UITableViewCell subclass :只需直接在 [=13] 上添加一些 UILabel 属性=] class,所以你不必在 cellForRowAtIndexPath 中创建它。但也许这种情况不适合你,因为标签的数量取决于 labelArray,这取决于单元格的位置。

您可以创建一个 UIView,其中将包含您所有的 UILabel。但是,当您 重用 开头的单元格时,只需从超级视图中删除该视图即可。 因此 masterview 将从您的单元格中删除

[[cell.contentView viewWithTag:101] removeFromSuperview]
UIView *yourViewName = [[UIView alloc]init];
// set your view's frame based on cell.
yourViewName.tag = 101;
for (int i = 0; i < [labelArray count]; i++) {
    UILabel tmpLabel = (UILabel )[self viewWithTag:100+i];
    if (tmpLabel == nil) 
    {
        tmpLabel = [UILabel alloc]initwithFrame .....];
        tmpLabel.tag = 100 + i;
        [yourViewName addSubview:tmpLabel];
    }
    tmpLabel.text = [labelArray objectAt:i];
}
[cell.contentView addSubView:yourViewName];

此过程也会加快单元格的滚动性能。

希望这个回答对您有所帮助。