views:

325

answers:

2

I'd like to set the title of a UIButton via code. I find myself having to call -[UIButton setTitle:forState:] for UIControlStateNormal, UIControlStateHighlighted, UIControlStateDisabled, UIControlStateSelected. And that doesn't even take into account all of the combinations of these states together.

Needless to say, this is tiresome. Is there a single call I can make that will set one string as the title for all of the states? (Since, I assume that in 95% of the cases, that's the desired behavior?)

+1  A: 

Yes, you certainly can. From the docs:

In general, if a property is not specified for a state, the default is to use the UIControlStateNormal value. If the value for UIControlStateNormal is not set, then the property defaults to a system value. Therefore, at a minimum, you should set the value for the normal state.

So just set the title for UIControlStateNormal and you're golden.

Shaggy Frog
In practice, I've found situations where it seems that's not true: text mysteriously disappearing when a button is clicked on, etc. That said, I'm not sure I can recreate those situations. If I discover a problem, I'll post it here. Thanks!
Greg Maletic
+1  A: 

Like Mr./Ms. Frog says, setting the title for UIControlStateNormal will usually do the trick. The only exception is if titles are already set for other states. UIControlState is a mask, so you can cover your butt like so:

[button setTitle:@"Title" forState:UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected]

If you're trying to be concise:

#define kAllControlStates (UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected)
[button setTitle:@"Title" forState:kAllControlStates];

Or concise and opaque:

[button setTitle:@"Title" forState:0xffff];

Update: I should have tested this before answering. It turns out a mask like UIControlStateHighlighted|UIControlStateDisabled indicates the state when the control is both highlighted and disabled. I had incorrectly assumed that that mask indicates "highighted or disabled". To conclude, you're better off with Mr. Frog's answer.

Tom
I found this didn't work for me. Text didn't show up on the button. I wonder if it's because UIControlStateNormal is equal to 0, making it fairly useless in a bit mask?
George Sealy
Mr. Frog :) 15chars
Shaggy Frog
@George: You're right. Looks like my answer was incorrect. I'll add a note.
Tom