我尝试创建一个按钮,在突出显示时将其背景颜色更改为标题标签的背景颜色,标题标签将其颜色更改为白色。我的代码是这样的:
import UIKit
class AlertStyleButton: UIButton {
var buttonColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
buttonColor = titleColor(for: .normal)
}
override var isHighlighted: Bool {
didSet {
guard let buttonColor = buttonColor else {
return
}
if isHighlighted {
UIView.animate(withDuration: 0.1, animations: {
self.setTitleColor(UIColor.white, for: UIControlState())
self.backgroundColor = buttonColor
})
} else {
UIView.animate(withDuration: 0.1, animations: {
self.setTitleColor(buttonColor, for: UIControlState())
self.backgroundColor = UIColor.white
})
}
}
}
}
按下按钮时按钮颜色似乎正确动画。但是,文本不会为白色设置动画。我在这里做错了什么?
答案 0 :(得分:0)
要设置UIButton
的标题颜色,您需要明确使用setTitleColor: forState:
方法。例如:
var buttonTextColor: UIColor!
var buttonBgColor: UIColor!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
buttonBgColor = UIColor.white // set whatever color you like
buttonTextColor = UIColor.black // set whatever color you like
backgroundColor = buttonBgColor
setTitleColor(buttonTextColor, for: .normal)
setTitleColor(buttonBgColor, for: .highlighted)
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
UIView.animate(withDuration: 0.1, animations: {
self.backgroundColor = self.buttonTextColor
})
} else {
UIView.animate(withDuration: 0.1, animations: {
self.backgroundColor = self.buttonBgColor
})
}
}
}