我知道必须调用超类的指定初始值设定项,我认为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 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")
}
答案 0 :(得分:0)
例如,如果name是您的必填字段,则在函数中实现所有初始设置。如果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
}
答案 1 :(得分:0)
init(type: UIButtonType)
不是UIButton的指定初始值设定项,init(frame: CGRect)
不是UIButton的指定初始值设定项
您只需要覆盖init(frame: CGRect)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button1 = MyButton(type: .custom)
}
}
class MyButton: UIButton {
// 初始化父类的指定构造器,然后你就可以获得父类的便利构造器
// overwrite the designated initializer of the super class, then you can automatically inherit the convenience initializer of the super class
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
如果要自定义按钮,可以添加convenience init(myType: UIButton.ButtonType)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button1 = MyButton(type: .custom)
let button2 = MyButton(myType: .custom)
}
}
class MyButton: UIButton {
// 初始化父类的指定构造器,然后你就可以获得父类的便利构造器
// overwrite the designated initializer of the super class, then you can automatically inherit the convenience initializer of the super class
override init(frame: CGRect) {
super.init(frame: frame)
}
// 创建自己的遍历构造器
// this is what you want
convenience init(myType: UIButton.ButtonType) {
self.init(type: myType) // called the convenience initializer which you automatically inherit from super class
// customize your own button
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
如果这对您有用,可以给我点赞(づ ̄ 3 ̄)づ