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

标签: iosswiftuibuttoncustom-button

解决方案


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

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

推荐阅读