我正在尝试通过将尽可能多的 View 相关内容推送到 Storyboard 以及自定义 UIView 类(即与在 UIViewController 上执行 View 相关内容相反)来清理我的代码并使用 MVC 原则
本身)
所以我有一个自定义的 UITableViewCell(称为 CustomCell
),它有几个属性,其中之一是我自己的 label
。因为我是从 Storyboard 中加载单元格,所以我使用 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;
}
这根本行不通.. 日志语句输出文本的 null
只是 b/c 文本尚未加载。 self.label
也是空的(我不知道为什么我认为它现在应该已经从 Nib 膨胀了)但即使我在这里初始化它..它仍然不会工作。
所以我的解决方法是将这个单元自定义部分简单地放在 TableViewController
中:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath {
UIFont *customFont = [UIFont fontWithName:@"Montserrat" size:16];
[((CustomCell *)cell).label setFont:customFont];
}
它工作得很好..我对这种方法不满意,我想知道如何让它在 CustomCell.m
更新: 让事情变得更有趣.. 如果我将 UITableViewCell 属性的自定义代码放在 initWithCoder 中,它们就可以工作了!考虑这个例子:
- (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;
}
这让这更奇怪了。
最佳答案
灵感来自 andykkt的评论,我在awakeFromNib中找到了解释文档:
The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.
所以这就解释了上面的奇怪行为:initWithCoder
实例化了一个标准的 UITableViewCell
(已经预烘焙了 backgroundView 等)..但是它仍然没有'无法识别我通过 Storyboard 添加到其中的 socket 。awakeFromNib
可以识别。
关于ios - 为什么 UITableViewCell 初始化在 initWithCoder 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19674002/