簡體   English   中英

自定義 UIButton 沒有點擊效果

[英]There is no tap effect for custom 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")
    }
}

是的,您不能從子類的 init 方法調用convenience init(type buttonType: UIButton.ButtonType) (因為子類必須調用超類的指定初始化程序),但您可以實現以下方法來創建具有系統類型的按鈕:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM