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.
- When I touch
normalBtn, state of this button changesnormaltoselected. - When I touch
normalBtnagain, its state changes fromselectedtonormal. - While these transitions,
highlightedproperty also should be changed, when I touchnormalBtn.
So my expectation of changing title is
- -> while touching -> (
normaltoselected) - -> while touching -> (
selectedtonormal)
But the result is,
- -> while touching -> (
normaltoselected) - -> (
selectedtonormal)
I really don't know why. Any ideas about this question? Thanks.