如何在通过 UITableViewCell 中的 XIB 加载的子视图中对标签和 UILabels/UIImageViews 进行初始样式设置

How to do initial styling of labels and UILabels/UIImageViews in a sub view which is loaded via an XIB in a UITableViewCell

我有一个 UITableViewCell,它有一个包含标签的子视图(在其内容视图内),以及一个图像视图和我需要设置的其他属性。

此子视图是从 XIB 设置的,因为它在应用程序的其他地方使用。我用

将它加载到单元格中
private func setup() {
    let nib = UINib.init(nibName: "AuthorHeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

然后,当加载单元格时,我在 awakeFromNib() 中设置了一些默认值。当我在那里有一个断点时,我可以看到 headerView: AuthorHeaderView 已经加载到内存中并且设置正确,但是它的标签和 imageView 还没有,它们是零,因此在尝试设置样式时它崩溃了这些观点。

如何对标签和图像视图以及通过 XIB 加载的子视图中的所有内容进行初始样式设置?

好的,所以我找到了解决方案。问题是我没有添加 init(coder aDecoder: NSCoder)

我有一个从 awakeFromNib 调用的设置方法,但我还需要从 initWithCoder 调用它。

示例:

override func awakeFromNib() {
    super.awakeFromNib()

    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    setup()
}

private func setup() {
    let nib = UINib.init(nibName: "HeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

无论如何,现在它完美运行了。希望这在某个阶段对其他人有帮助:-)