为什么UITableViewCell初始化在initWithCoder中不起作用

abb*_*ood 4 objective-c storyboard uitableview ios

我正在尝试清理我的代码并使用MVC原则,将尽可能多的视图相关内容推送到故事板以及自定义UIView类(即与在UIViewController自身上查看相关内容相反)

所以我有一个自定义的UITableViewCell(被称为CustomCell),它有几个属性,其中一个是我自己的label.因为我正在从故事板加载单元格,所以我初始化它initWithCoder而不是initWithStyle:reuseIdentifier:,这就是我所拥有CustomCell.m的子类UITableViewCell(由于某种原因,我无法弄清楚如何使用storyboard设置自定义字体..但是这不是这个问题的重点):

// CustomCell.m - subclass of UITableViewCell
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        NSLog(@"customizing cell font having text %@", self.label.text);
        UIFont *customFont = [UIFont fontWithName:@"Montserrat" size:16];
        self.label.textColor = [UIColor redColor];
        [self.label setFont:customFont];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

这根本不起作用..日志语句输出null文本只是b/c尚未加载文本.self.label也是null(我不知道为什么我认为它现在应该从笔尖膨胀)但是即使我在这里初始化它仍然无效.

所以我的工作就是简单地将这个单元格自定义部分放在TableViewController:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell 
forRowAtIndexPath:(NSIndexPath *)indexPath {        
    UIFont *customFont = [UIFont fontWithName:@"Montserrat" size:16];
    [((CustomCell *)cell).label setFont:customFont];
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好..我对这种方法不满意,我想知道如何让它从内部起作用 CustomCell.m

更新:使事情变得更有趣..如果我在initWithCoder中放置UITableViewCell属性的自定义代码,它们可以工作!考虑这个例子:

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIView *bgColorView = [[UIView alloc] init];
        [bgColorView setBackgroundColor:[UIColor blueColor]];
        [self setSelectedBackgroundView:bgColorView];  // actually works!
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

这使得这更加奇怪.

abb*_*ood 7

受到andykkt评论的启发,我在awakeFromNib文档中找到了解释:

nib加载基础结构将awakeFromNib消息发送到从nib归档重新创建的每个对象,但只有在归档中的所有对象都已加载并初始化之后.当一个对象收到一个awakeFromNib消息时,它保证已经建立了所有的插座和动作连接.

所以这解释了上面的奇怪行为:initWithCoder实例化一个标准UITableViewCell(已经预先带有backgroundView等等)但是它仍然无法识别我通过故事板添加到它的插座.. awakeFromNib的确如此.