Swift 中設置按鈕(UIButton)在不同狀態下的樣式

設置一個按鈕在不同的狀態下顯示不同的樣式是很常見的需求,于是我馬上想到以下代碼:? ??

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 ? ?

}


顯示正常~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容