我知道必须调用超类的指定初始值设定项,我认为init(type: UIButtonType)
已经调用了指定的初始值设定项,为什么我不能在易理解初始值设定项中使用“self.init(type:.custom)”,我的子类是UIButton
问题描述:
?所以我用它在子类方便初始化,但失败我知道必须调用超类的指定初始值设定项,我认为<code>init(type: UIButtonType)</code>已经调用了指定的初始值设定项,为什么我不能在易理解初始值设定项中使用“self.init(type:.custom)”,我的子类是UIButton
class TSContourButton: UIButton {
enum ContourButtonSizeType {
case large
case small
}
convenience init(type:ContourButtonSizeType) {
self.init(type: .custom)
}
然后,我试了这个。它编译好。但是,它看起来不专业
class TSClass: UIButton {
convenience init(frame: CGRect, myString: String) {
self.init(frame: frame)
self.init(type: .custom)
}
所以,我怀疑我可能会认为错了。所以,我做了一些测试。它成功地称为super convenience initializer
。为什么我不能在方便初始值设定项中使用self.init(type: .custom)
在我的子类UIButton
?
class person: UIButton {
var name: String = "test"
override init(frame: CGRect) {
super.init(frame: .zero)
self.name = "one"
}
convenience init(myName: String) {
self.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class man: person {
convenience init(mySex: Int) { // it successfully call superclass convenience initializer
self.init(myName: "info")
}
答
如果,比方说,名字是你的必填字段,你实现你所有的初始的功能设置。如果name
不可用,你应该处理。如果没有提供类型,我会保留small
作为默认选项。
// MARK:- Designated Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup(type: .small)
}
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup(type: .small)
}
// MARK:- Convenience Initializers
convenience init(type: ContourButtonSizeType) {
self.init(frame: .zero)
initialSetup(type: type)
}
func initialSetup(type: ContourButtonSizeType) {
// handle all initial setup
}
'所以我用它在子类方便初始化,但失败' - 你得到什么错误? – BaSha