情节提要中的自定义 UITableViewCells 的问题



我需要创建一个显示四个UILabel实例的自定义UITableViewCell

在此自定义单元格的实现中,我有以下初始化代码:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // configure labels
        self.positionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)];
        self.positionLabel.textColor = [UIColor whiteColor];
        self.positionLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0f];
        [self addSubview:self.positionLabel];
    }
    return self;
}

在我的cellForRowAtIndexPath方法中,我有以下代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CustomUICell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    if (cell == nil) {
         cell = [[CustomUICell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
        cell.positionLabel.text = @"Test";
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

但是,与其使用 initWithFrame:CGRectMake(5, 10, 300, 30)]; 创建单元格,我更愿意在我的故事板中执行此操作。如果我将标签拖到情节提要中的单元格上,并将其连接到相应的属性,如下所示:

@property (nonatomic) IBOutlet UILabel *positionLabel;

并通过编写以下内容创建我的标签:

self.positionLabel = [[UILabel alloc] init];

我希望在运行应用程序时在我的单元格中看到一个标签,但这不会发生。有没有人知道我错过/不理解什么?谢谢!

首先,使用 dequeueReusableCellWithIdentifier:forIndexPath: 而不是 dequeueReusableCellWithIdentifier: 。在这种情况下,您不需要if子句。

关于您的问题:在情节提要中添加单元格时,无需实现initWithStyle:reuseIdentifier:。实际上,如果这样做,则会执行代码路径并覆盖您在情节提要中执行的所有操作。

最新更新