Reputation: 1679
I got a strange UIButton
result while understanding concept of UIControlState
. Here is my simple code related to 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
}
}
Here is my scenario about this code.
normalBtn
, state of this button changes normal
to
selected
. normalBtn
again, its state changes from
selected
to normal
. highlighted
property also should be changed, when I touch normalBtn
.So my expectation of changing title is
normal
to selected
)selected
to normal
)But the result is,
normal
to selected
)selected
to normal
)I really don't know why. Any ideas about this question? Thanks.
Upvotes: 1
Views: 649
Reputation: 1325
Try adding selected state combining with highlighted state.
Example:
button.setTitle("😆", for: UIControlState.selected.union(.highlighted))
Upvotes: 3
Reputation: 69
Alternative syntax to the accepted answer:
button.setTitle("😆", for: [.selected, .highlighted])
Upvotes: 0