1

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.

Changnam Hong
  • 1,669
  • 18
  • 29

2 Answers2

3

Try adding selected state combining with highlighted state.

Example:

button.setTitle("", for: UIControlState.selected.union(.highlighted))
Zoe
  • 27,060
  • 21
  • 118
  • 148
Van
  • 1,225
  • 10
  • 18
  • 1
    as @sivajee said:" the highlighted state won't come from Selected to normal transition", so apple provides way to combine states together, just like in your case. and since highlight state comes before the selected/normal state, your case is satisfying. :) – Van Nov 20 '17 at 07:35
  • Thank you for your explanation! Now I understand how to use it. – Changnam Hong Nov 20 '17 at 07:54
  • my pleasure . :) – Van Nov 20 '17 at 12:16
0

Alternative syntax to the accepted answer:

button.setTitle("", for: [.selected, .highlighted])
Zoe
  • 27,060
  • 21
  • 118
  • 148