我知道必须调用父类(super class)的指定初始值设定项,我认为 init(type: UIButtonType)
已经调用了指定初始值设定项,因此我在子类便利初始值设定项中使用它,但失败了
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 便利初始化程序
。为什么我不能在 UIButton
子类的便捷初始化程序中使用 self.init(type: .custom)
?
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
}
关于ios - 为什么我不能在 UIButton 子类的便捷初始化程序中使用 "self.init(type: .custom)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41458441/