设置一个按钮在不同的状态下显示不同的样式是很常见的需求,于是我马上想到以下代码:
let button = UIButton.init(frame: CGRect.init(x: 0, y: 200, width: kWidth, height: 50))
button.setTitle("选中了", for: .selected)
button.setTitleColor(.red, for: .selected)
button.setTitle("没选中", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(buttonAction(button:)),for:.touchUpInside)
view.addSubview(button)
@objc private func buttonAction(button : UIButton) {
button.isSelected = !button.isSelected
}
看上去没问题,分别设置了按钮在 normal 状态下和 selected 状态下的标题和标题颜色。但实际上会有一个小问题,那就是当按钮在手指按压不抬起手指的时候按钮会显示成 normal 状态下的样式。
添加以下代码,我们来查看一下按钮在被手指按压不抬起手指的时候 state 属性的值。
button.addTarget(self, action: #selector(buttonAction(button:)), for:.touchDown)
view.addSubview(button)
@objc private func buttonTouchDownAction(button : UIButton){
let status = button.state
}
断点调试得知,当按钮在 status = .normal 时再被按压并手指未抬起时 :
status = UIControlState [.normal, .highlighted]
断点调试得知,当按钮在 status = .selected 时再被按压并手指未抬起时 :
status = UIControlState [.normal, .highlighted, .selected]
原来如此,将代码改为:
let button = UIButton.init(frame: CGRect.init(x: 0, y: 200, width: kWidth, height: 50))
button.setTitle("选中了", for: .selected)
button.setTitleColor(.red, for: .selected)
button.setTitle("选中了", for: [.normal,.highlighted,.selected]) button.setTitleColor(.red, for: [.normal,.highlighted,.selected])
button.setTitle("没选中", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(buttonAction(button:)),for:.touchUpInside)
view.addSubview(button)
@objc private func buttonAction(button : UIButton) {
button.isSelected = !button.isSelected
}
显示正常~