Changing a UIButton title and dealing with button States

If you are changing the title of a UIButton programmatically, you will naturally use the method setTitle:forState:. Easy enough… well, sort of. What do you put in the state parameter?

My first reaction was “I’m going to put all possible states since I just want the button title to change no matter what.” So I blindly bit-OR‘ed all the possible values defined in the docs.


[myButton setTitle:@"New Title" 
          forState:UIControlStateNormal | UIControlStateHighlighted | UIControlStateDisabled | UIControlStateSelected];

Sound reasonable right? Wrong. If you do that here, your button title is probably not going to change at all. The problem is that the “normal” state (per Apple docs that’s “enabled, not selected, not highlighted”) is defined as such:

enum {
    UIControlStateNormal   = 0,
    UIControlStateHighlighted  = 1 << 0,
    UIControlStateDisabled     = 1 << 1,
    UIControlStateSelected     = 1 << 2,
    ...
}

so if you bit-OR all of them you are actually going to set the title for ALL states EXCEPT the “normal” (most common) state!

Sigh…

Advertisements

One thought on “Changing a UIButton title and dealing with button States

  1. Also, I have noticed one thing that… If the button in disabled state and you are trying to change the title of normal state, it wont work. I had to change the state to enabled and then I could manipulate title and set back to disabled.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s