ios – 在initWithCoder中定制自定义UITableViewCell:不工作

我有一些自定义UITableViewCell的问题以及如何使用故事板管理事物.当我将样式代码放在initWithCoder中时:它不起作用,但如果我把它放在tableView:cellForRowAtIndexPath中:它可以工作.在storyboard中我有一个原型单元格,其class属性设置为我的UITableViewCell自定义类.现在initWithCoder中的代码被调用了.

SimoTableViewCell.m

@implementation SimoTableViewCell

@synthesize mainLabel,subLabel;

-(id) initWithCoder:(NSCoder *)aDecoder {
    if ( !(self = [super initWithCoder:aDecoder]) ) return nil;

    [self styleCellBackground];
    //style the labels
    [self.mainLabel styleMainLabel];
    [self.subLabel styleSubLabel];

    return self;
}

@end

TableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NearbyLandmarksCell";
    SimoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    //sets the text of the labels
    id<SimoListItem> item = (id<SimoListItem>) [self.places objectAtIndex:[indexPath row]];
    cell.mainLabel.text = [item mainString];
    cell.subLabel.text = [item subString];

    //move the labels so that they are centered horizontally
    float mainXPos = (CGRectGetWidth(cell.contentView.frame)/2 -      CGRectGetWidth(cell.mainLabel.frame)/2);
    float subXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.subLabel.frame)/2);
    CGRect mainFrame = cell.mainLabel.frame;
    mainFrame.origin.x = mainXPos;
    cell.mainLabel.frame = mainFrame;
    CGRect subFrame = cell.subLabel.frame;
    subFrame.origin.x = subXPos;
    cell.subLabel.frame = subFrame;

    return cell;
}

我调试了代码并发现首先调用了dequeue …然后它进入initWithCoder:然后返回到视图控制器代码.奇怪的是,记忆中细胞的地址在返回自我之间变化;当它回到控制器.如果我在出列后将样式代码移回视图控制器……一切正常.只是我不想在重复使用单元格时做不必要的样式.

干杯

解决方法

在单元格上调用initWithCoder:之后,将创建单元格并设置其属性.但是,单元格上的XIB(IBOutlets)中的关系尚未完成.因此,当您尝试使用mainLabel时,它是一个零引用.

将样式代码移动到awakeFromNib方法.在解压缩XIB之后,在创建单元并完全配置单元后调用此方法.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...