0

我有以下自定义按钮:

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(),它的字体是可以的,但它的标题并不模糊。如何解决问题?

4

2 回答 2

1

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

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)
}
于 2020-08-20T17:38:38.517 回答
1

您还可以通过以下方式实现此目的:

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)
    }
}
于 2020-08-20T17:47:14.210 回答