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 changesnormal
toselected
. - When I touch
normalBtn
again, its state changes fromselected
tonormal
. - While these transitions,
highlighted
property also should be changed, when I touchnormalBtn
.
So my expectation of changing title is
- -> while touching -> (
normal
toselected
) - -> while touching -> (
selected
tonormal
)
But the result is,
- -> while touching -> (
normal
toselected
) - -> (
selected
tonormal
)
I really don't know why. Any ideas about this question? Thanks.