Is there a way to setTitle on a UIButton that updates all UIControlStates at once?

Viewed 15095

I have a UIButton, and I'd like to update its title, but I'd rather not have to always do it for each and every state like the following:

[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Play" forState:UIControlStateHighlighted];
[myButton setTitle:@"Play" forState:UIControlStateSelected];

Is there a better way?

5 Answers

2019

It's just

yourButton.setTitle("Click me", for: .normal)

The answer:

button.setTitle("All", for: .normal)

or

button.setTitle("All", for: [])

is not correct in general, because it works only if the title for some state is not already set. For example:

button.setTitle("N", for: .normal)
button.setTitle("HL", for: .highlighted)
button.setTitle("All", for: .normal)

After this code button still have title "HL" for highlighted state. So to change title for all used states in general case, you have to loop through all these states:

let states: [UIControl.State] = [.normal, .highlighted, .selected, [.highlighted, .selected]]
for state in states {
  button.setTitle("All", for: state)
}

(If you use other states e.g. .disabled, you have to add they combinations to loop as well)

Note: UIControl.State is a Set of options, so setting the title with:

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

does not set title "All" for both selected and highlighted states, instead it sets the title "All" for the combined state which is selected and highlighted at the same time.

Related