I have a subclass of UIButton and when I add the button to my view controller in my storyboard, my app crashes with fatalError("init(coder:) has not been implemented"
). If I manually add the subclassed button in code it works fine. What am I doing wrong?
import UIKit
class RAPanicButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = true
self.clipsToBounds = true
self.backgroundColor = .red
self.setTitle("Panic!", for: .normal)
self.titleLabel?.textColor = .white
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
}
答案 0 :(得分:4)
情节提要中的内容将通过调用init(coder:)
初始化程序来初始化。这意味着,如果要在情节提要中使用视图,则不得在fatalError
中插入init(coder:)
。
您可以在两个初始化器中放入相同的代码:
func setup() {
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = true
self.clipsToBounds = true
self.backgroundColor = .red
self.setTitle("Panic!", for: .normal)
self.titleLabel?.textColor = .white
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}