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

标签 ios objective-c uitableview storyboard

我正在尝试通过将尽可能多的 View 相关内容推送到 Storyboard 以及自定义 UIView 类(即与在 UIViewController 上执行 View 相关内容相反)来清理我的代码并使用 MVC 原则 本身)

所以我有一个自定义的 UITableViewCell(称为 CustomCell),它有几个属性,其中之一是我自己的 label。因为我是从 Storyboard 中加载单元格,所以我使用 initWithCoder 而不是 initWithStyle:reuseIdentifier: 对其进行初始化,这就是我在 CustomCell.mUITableViewCell 的子类(出于某种原因我无法弄清楚如何使用 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/

相关文章:

iOS UITableView contentOffset 当键盘显示时

ios - UIImage(文件内容:) returning nil despite file existing in caches directory

ios - 如何从 swift 4 上的 didFinishLaunchingWithOptions 获取 Notificationcenter 数据

ios - 我怎样才能在应用程序商店中获得应用程序的价格?

objective-c - 右键单击 NSWindow 选项卡,将其他菜单项添加到上下文菜单

iphone - TableView 为每个 View 添加相同的功能

ios - iOS 版 Simperium 中的 API key

ios - 如何查看()的内容

iphone - 如何在 iphone sdk 中以字符串形式发送 xml?

swift - 在 swift 中创建自定义 tableview 单元格