Strange state change(UIControlState) of UIButton

639 Views Asked by At

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.

  1. When I touch normalBtn, state of this button changes normal to selected.
  2. When I touch normalBtn again, its state changes from selected to normal.
  3. While these transitions, highlighted property also should be changed, when I touch normalBtn.

So my expectation of changing title is

  1. -> while touching -> (normal to selected)
  2. -> while touching -> (selected to normal)

But the result is,

  1. -> while touching -> (normal to selected)
  2. -> (selected to normal)

I really don't know why. Any ideas about this question? Thanks.

2

There are 2 best solutions below

3
Vanita L. On BEST ANSWER

Try adding selected state combining with highlighted state.

Example:

button.setTitle("", for: UIControlState.selected.union(.highlighted))
0
Stanislav M. On

Alternative syntax to the accepted answer:

button.setTitle("", for: [.selected, .highlighted])