在iOS中触摸时如何模糊自定义按钮的标题如系统UIButton的标题?

问题描述

我有以下自定义按钮:

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(),则其字体可以,但标题不会模糊。如何解决该问题?

解决方法

为突出显示的状态设置不同的颜色:

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)
    }
}