Search code examples
iosswiftuibuttoncustom-button

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


I have following custom button:

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

But I want its title to blur when touching, just like how system UIButton behaves. If I declare my button like this GreenButton(type: .system), its title blurs, but font is not changing. If I declare it as GreenButton(), its font is ok, but its title is not blurring. How to fix the problem?


Solution

  • Set a different color for the highlighted 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)
    }