自定义视图 - 在 "required init?(coder aDecoder: NSCoder)" 方法中崩溃

Custom view - Crash in "required init?(coder aDecoder: NSCoder)" method

代码:

class HeaderView: UIView {

@IBOutlet weak var titleLabel: UILabel!

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

func finishInit() {
    titleLabel.backgroundColor = UIColor.white
}

func setView(withTitle title: String?) {
    titleLabel.backgroundColor  = UIColor.white
    titleLabel.text = title

}

崩溃:

在 finishInit() 方法中,同时设置标签背景颜色

fatal error: unexpectedly found nil while unwrapping an Optional value

但同样,在 setView() 方法上,没有崩溃。

init方法运行和return时,插座的连接还没有建立。因此插座仍然nil,你在使用它时会崩溃。

您应该能够通过在 titleLabel 之后添加一个问号 (?) 来对此进行测试,从而再次将其视为可选项。

titleLabel?.backgroundColor = UIColor.white

那么你不会崩溃,但如果标签仍然是 nil,该行当然也不会做任何事情。

所以您需要稍后调用使用插座的代码(您似乎正在使用 setView?

您可以在应该设置插座的地方使用 awakeFromNib