ios - 为什么我不能在 UIButton 子类的便捷初始化程序中使用 "self.init(type: .custom)"

标签 ios swift uibutton initializer convenience-methods

我知道必须调用父类(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/

相关文章:

ios - 使 UIButton 大于其图像

ios - Swift 3 - 基于按钮状态的 If else 语句

ios - 如何将参数传递到 PhoneGap 应用程序中的本地页面?

swift - 下载自定义 CoreML 模型并加载以供使用 [Swift]

ios7 - 如何在 iOS 7 上获得拨号盘蜂鸣声

ios - 触摸一次后如何使 UIButton 不可点击并隐藏和取消隐藏按钮? - swift

javascript - "Preload"apple-touch-precomposed-icon 添加到主屏幕之前?

ios - 使用 React Native 在 IOS 运行时出现 "Unhandled JS Exception: Native module cannot be null"错误

ios - SceneKit 场景大小不正确

SwiftUI:如何使用@Binding 变量实现自定义初始化