首页 > 解决方案 > 自定义 UIButton 没有点击效果

问题描述

当我初始化 UIButton 时,我可以在它的 init 中提供它的类型。但是,如果我使用自定义按钮,我不能给它一个类型,因为 buttonType 属性是 get-only,我也不能把它放在 init 函数中。

class Button: UIButton {
    init(placeholder: String) {
        super.init(frame: .zero)
        setTitle(placeholder, for: .normal)
        setTitleColor(.white, for: .normal)
        backgroundColor =  colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1).withAlphaComponent(0.5)
        layer.cornerRadius = 5
        setHeight(50)
        titleLabel?.font = .boldSystemFont(ofSize: 20)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

标签: iosswift

解决方案


是的,您不能convenience init(type buttonType: UIButton.ButtonType)从子类的 init 方法调用(因为子类必须调用超类的指定初始化程序),但您可以实现以下方法来创建具有系统类型的按钮:

class Button: UIButton {
    static func systemButton(placeholder: String) -> Button {
        let button = Button(type: .system)
        button.setTitle(placeholder, for: .normal)
        // ...
        return button
    }
}

推荐阅读