如何在 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()
,它的字体没问题,但它的标题不模糊。如何解决问题?
为高亮状态设置不同的颜色:
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)
}
}
我有以下自定义按钮:
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)
}
}