簡體   English   中英

自定義視圖-“必需的init?(編碼器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方法並返回時,尚未建立出口的連接。 因此,插座仍然nil ,使用時會崩潰。

您應該能夠通過在titleLabel之后添加一個問號(?)並再次將其titleLabel可選內容來進行測試。

titleLabel?.backgroundColor = UIColor.white

這樣,您就不會崩潰,但是如果標簽仍然為零,該行當然也不會做任何事情。

因此,您稍后需要調用使用插座的代碼(您似乎正在使用setView進行此setView

您可以在應該設置出口的地方使用awakeFromNib

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM