我試圖清理我的代碼,並通過推入儘可能多的視圖相關的東西,我可以進入故事板以及自定義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