有時(shí)候我們?cè)趯?shí)現(xiàn)自定義的 UIView 控件的時(shí)候,會(huì)重寫(xiě)它們的系統(tǒng)構(gòu)造方法抹腿,如下的兩個(gè)構(gòu)造方法:
override init(frame CGRect){
super.init(frame: frame)
}
required init?(coder: NSCoder){
super.init(coder: coder)
fatalError("init(coder:) has not been implemented")
}
這兩個(gè)方法的區(qū)別在于彤路,如果你使用代碼傳入 frame 布局浅浮,則會(huì)調(diào)用 override init(frame CGRect)
而如果使用 xib/storyboard 則沫浆,會(huì)調(diào)用 required init?(coder: NSCoder)
fatalError("init(coder:) has not been implemented")
這段代碼會(huì)讓程序crash
在所有的 UIView 及其子類(lèi)在開(kāi)發(fā)中,如果重寫(xiě)了構(gòu)造方法滚秩,就必須要實(shí)現(xiàn) initWithCode 方法专执,保證提供兩種實(shí)現(xiàn)方式。因?yàn)槿绻褂?xib 創(chuàng)建 和布局 UIView郁油,它是不會(huì)走 initWithFrame 方法的本股,反正亦然。
class DemoLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
fatalError("init(coder:) has not been implemented")
}
}