簡體   English   中英

在 iOS 中觸摸時如何模糊自定義按鈕的標題,如系統 UIButton 的標題?

[英]How to blur custom button's title like system UIButton's title when touching in iOS?

我有以下自定義按鈕:

class GreenButton: UIButton {

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {
    backgroundColor = .green
    layer.cornerRadius = 4
    setTitleColor(.white, for: .normal)
    titleLabel?.font = .systemFont(ofSize: 22, weight: .bold)
}
}

但我希望它的標題在觸摸時模糊,就像系統 UIButton 的行為方式一樣。 如果我像這樣聲明我的按鈕GreenButton(type: .system) ,它的標題會模糊,但字體不會改變。 如果我將它聲明為GreenButton() ,它的字體是可以的,但它的標題並不模糊。 如何解決問題?

為突出顯示的 state 設置不同的顏色:

private func setup() {
    backgroundColor = .green
    layer.cornerRadius = 4
    // set title normal color
    setTitleColor(.white, for: .normal)
    // set title highlighted color
    setTitleColor(.gray, for: .highlighted)
    titleLabel?.font = .systemFont(ofSize: 22, weight: .bold)
}

您還可以通過以下方式實現此目的:

class GreenButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setTitleColor(UIColor(white:1.0 , alpha: 0.5), for: .normal)
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        setTitleColor(.white, for: .normal)
    }

    private func setup() {
        backgroundColor = .green
        layer.cornerRadius = 4
        setTitleColor(.white, for: .normal)
        titleLabel?.font = .systemFont(ofSize: 22, weight: .bold)
    }
}

暫無
暫無

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

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