設(shè)置一個按鈕在不同的狀態(tài)下顯示不同的樣式是很常見的需求,于是我馬上想到以下代碼:? ??
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 ? ?
}
看上去沒問題,分別設(shè)置了按鈕在?normal 狀態(tài)下和?selected 狀態(tài)下的標(biāo)題和標(biāo)題顏色。但實(shí)際上會有一個小問題,那就是當(dāng)按鈕在手指按壓不抬起手指的時候按鈕會顯示成?normal 狀態(tài)下的樣式。
添加以下代碼,我們來查看一下按鈕在被手指按壓不抬起手指的時候?state 屬性的值。
button.addTarget(self, action: #selector(buttonAction(button:)), for:.touchDown)?
view.addSubview(button)
@objc private func buttonTouchDownAction(button : UIButton){? ? ? ?
????????let status = button.state?? ? ? ?? ?
}
斷點(diǎn)調(diào)試得知,當(dāng)按鈕在 status = .normal 時再被按壓并手指未抬起時 :
status = ?UIControlState [.normal, .highlighted]
斷點(diǎn)調(diào)試得知,當(dāng)按鈕在 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 ? ?
}
顯示正常~