【问题标题】:Subclass of UIButton cant call the buttonType initializerUIButton 的子类不能调用 buttonType 初始化器
【发布时间】:2018-05-21 05:32:16
【问题描述】:

我正在尝试对UIButton 进行子类化,以便它的默认初始化程序将其设置为与调用UIButton(type: UIButtonType.roundedRect) 时相同的方式。但是,由于某些 Swift 限制,我无法说明这不是指定的初始化程序。此外,buttonType 属性是只读的。

如何在 Swift 中做到这一点?

作为参考,此代码无法编译,因为我没有调用指定的初始化程序。

class ToggleButton : UIButton {
    init() {
        super.init(type: UIButtonType.roundedRect)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("TROUBLE")
    }
}

【问题讨论】:

标签: ios swift uibutton initialization uikit


【解决方案1】:

Swift 使用初始化器可能有点烦人。这应该会为您完成。

class ToggleButton : UIButton {
    convenience init() {
        self.init(type: .roundedRect)
    }
    
    convenience init(type buttonType: UIButtonType) {
        self.init(type: buttonType)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("TROUBLE")
    }
}

编辑:21 年 2 月 12 日

从 Swift 5 开始,这可以通过以下方式完成。

class ToggleButton: UIButton {
    convenience init() {
        self.init(type: .roundedRect)
    }
}

【讨论】:

  • 如果我有ToggleButton 类型的插座,如何致电convenience init(type buttonType: UIButtonType)
  • 这不起作用。它会创建一个无限循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
相关资源
最近更新 更多