[英]Change UIButton backgroundColor on UIControlState.Highlighted?
[英]Strange state change(UIControlState) of UIButton
在理解UIControlState
概念時,我得到了一個奇怪的UIButton
結果。 這是我與UIButton
相關的簡單代碼。
import UIKit
class ViewController: UIViewController {
let normalBtn: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 80, y: 200, width: 200, height: 100)
button.setTitle("🙂", for: .normal)
button.setTitle("😆", for: .highlighted)
button.setTitle("😍", for: .selected)
button.setTitle("😂", for: .focused)
button.titleLabel?.font = UIFont.systemFont(ofSize: 50)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(normalBtn)
normalBtn.addTarget(self, action: #selector(btnSelected), for: .touchUpInside)
}
@objc func btnSelected() {
print("highlight", normalBtn.isHighlighted)
normalBtn.isSelected = !normalBtn.isSelected
}
}
這是我關於此代碼的場景。
normalBtn
,此按鈕的狀態變為normal
到selected
。normalBtn
時,它的狀態從selected
變為normal
。normalBtn
時,雖然這些轉換, highlighted
屬性也應該改變。所以我對改變標題的期望是
normal
selected
)selected
normal
)但結果是,
normal
selected
)selected
normal
)我真的不知道為什么。 關於這個問題的任何想法? 謝謝。
嘗試將選定狀態與突出顯示狀態相結合。
例子:
button.setTitle("😆", for: UIControlState.selected.union(.highlighted))
已接受答案的替代語法:
button.setTitle("😆", for: [.selected, .highlighted])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.