UILabel在UITableViewCell中多次出现

时间:2015-09-22 22:43:58

标签: ios objective-c uitableview

我目前正在以编程方式创建我的UITableViewCells:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home-Cell" forIndexPath:indexPath];
    if (cell == nil) {
        UILabel *newLabel = [[UILabel alloc] initwithframe:cell.frame];
        [cell addSubview:newLabel];
    }
    [newLabel setText:self.data[indexPath.row]];

    return cell;
}

这似乎每次重复使用单元格时都会创建一个新的UILabel,我绝对不想要。我尝试了以下操作:

$('.myclass').css('color','#900');
$('.myclass').html('invalid');

然后似乎永远不会创建UILabel。也许这是因为我正在使用具有故事板的原型单元格,因此单元格永远不会为零?

4 个答案:

答案 0 :(得分:2)

你有两个解决方案。

  1. 创建已具有标签的自定义表格视图单元格。
  2. 如果要在代码中添加标签,请不要为单元格注册类。然后出列的单元格可以是nil,您可以在那时添加标签(就像在第二组代码中一样)。这也需要使用不dequeueReusableCellWithIdentifier的{​​{1}}方法。

答案 1 :(得分:0)

您应该创建一个UITableViewCell子类并添加“newLabel”作为属性。

答案 2 :(得分:0)

单元格永远不会为nil,因为用于使表格视图单元格出列的方法始终返回一个单元格,如果它在重用队列中尚不存在,则创建一个单元格。

更好的解决方案是在故事板中的单元原型中创建标签。

答案 3 :(得分:0)

此实现针对MVC架构,其中控制器管理器填充并且不处理视图。在这里,您尝试从控制器添加视图中的内容。建议将UITableViewCell子类化如下,并在其中添加自定义UI控件

<强> MyTableViewCell.h

@interface MyTableViewCell : UITableViewCell {

}

@property (nonatomic, strong) UILabel *myLabel;


@end

然后,您可以在layoutSubviews文件中实施MyTableViewCell.m来定义单元格的外观。

<强> MyTableViewCell.m

- (id)initWithStyle:(UITableViewCellStyle)iStyle reuseIdentifier:(NSString *)iReuseIdentifier {
    if ((self = [super initWithStyle:iStyle reuseIdentifier:iReuseIdentifier])) {
        self.myLabel = [[UILabel alloc] initWithFrame:<Your_Frame>];
        // Set more Label Properties
        [self.contentView addSubview:self.myLabel];
    }

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    // Override run time properties
}

最后使用您的自定义单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Home-Cell" forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Home-Cell"];
    }

    cell.myLabel.text = self.data[indexPath.row];

    return cell;
}

作为旁注,我希望您知道textLabeldetailTextLabel免于默认UITableViewCell实施。

相关问题