有时候可能会有这样的需求,在button高亮(highlighted)的状态下改变背景颜色(backgroundColor)或者边框颜色(bordercolor)或者字体颜色,那么我们怎么来处理这个问题呢?下面就以改变边框颜色为例子,默认边框为灰色,高亮状态下为红色,下面看看2种实现方式
1为button添加对应的点击事件,实现简单,直接看代码
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.layer.borderColor = UIColor.gray.cgColor
button.layer.borderWidth = 2
button.addTarget(self, action: #selector(highlightBorder), for: .touchDown)
button.addTarget(self, action: #selector(normalBorder), for: .touchUpInside)
}
func highlightBorder() {
print("highlightBorder")
button.layer.borderColor = UIColor.red.cgColor
}
func normalBorder() {
print("normalBorder")
button.layer.borderColor = UIColor.gray.cgColor
}
}
分析:默认情况下,边框为灰色,当我们按钮按钮的时候,边框变为红色,当松开按钮时又回到正常灰色边框,这里功能的实现需要明确按钮事件的触发时机。
touchDown,单点触摸按下事件:用户点触屏幕,或者又有新手指落下的时候。
touchUpInside.所有在控件之内触摸抬起事件。
touchUpInside在touchDown之后进行调用,所以能够实现我们的需求。
2自定义UIButton,重写isHighlighted属性
重写isHighlighted属性,设置对应的边框颜色
class MyButton: UIButton {
override var isHighlighted: Bool {
didSet {
switch isHighlighted {
case true:
layer.borderColor = UIColor.red.cgColor
case false:
layer.borderColor = UIColor.gray.cgColor
}
}
}
}
ViewController仅仅是持有MyButton实例,并且设置默认边框颜色
class ViewController: UIViewController {
@IBOutlet weak var myButton: MyButton!
override func viewDidLoad() {
super.viewDidLoad()
myButton.layer.borderColor = UIColor.gray.cgColor
myButton.layer.borderWidth = 2
}
}