我试图清理我的代码,并通过推入尽可能多的视图相关的东西,我可以进入故事板以及自定义UIView类使用MVC原则(即相对于做视图相关的东西在UIViewController
本身)为什么UITableViewCell初始化不工作在initWithCoder
所以我有一个自定义的UITableViewCell(称为CustomCell
),有几个属性,其中之一是我自己的label
。由于我正在从故事板加载单元格,因此我使用initWithCoder
而不是initWithStyle:reuseIdentifier:
对其进行了初始化,这是我在CustomCell.m
中的一个子类,它是UITableViewCell
的子类(出于某种原因,我无法弄清楚如何使用自定义字体故事板..但是这是这个问题的跑题了):
// 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;
}
这根本不起作用。对于文本只是b/C的文本日志语句输出null
尚未加载。 self.label
也是空的(我不知道为什么我认为它现在应该已经从笔尖膨胀),但即使我在这里初始化它..它仍然不会工作。
所以我的解决办法是简单地在这里把这个细胞的定制部分的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;
}
这使得这更奇怪。
也许'initWithCoder:'方法在后台线程上。用'performSelectorOnMainThread:withObject:waitUntilDone:' – theShay
尝试原谅另一个方法的代码。使用awakeFromNib来初始化你的控件,我认为这是最好的函数,但它可以被多次调用。 – andykkt
@theShay我的更新表明,这与后台线程无关 – abbood