UIButton Title Text Does Not Display
by Warlock on May.14, 2009, under Cocoa
Ran into a minor problem today when I was attempting to manually create a UIButton in my iPhone app. I attempted to create/configure the button through code similar to the following:
CGRect frame = CGRectMake(0, 0, 200, 52);
UIButton b = [[UIButton alloc] initWithFrame:frame];
b.titleLabel.text = @"My Button";
b.titleLabel.textColor = [UIColor whiteColor];
b.backgroundColor = [UIColor clearColor];
The key mistake is highlighted in red. I attempted to manually set the text an color of the UIButton’s label, when in fact the UIButton would automatically reconfigure the label (including it’s text) in response to state changes.
The correct approach is to use send the setXXX:forState: messages to the UIButton object itself. For example, the following code sets the text/color for the UIControlStateNormal state.
[b setTitle:@"Test" forState:UIControlStateNormal];
[b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
May 21st, 2009 on 7:59 am
Hello Ryan,
Thanks for this tip, great help
July 8th, 2009 on 6:25 pm
Thanks, saved me some time!
July 19th, 2009 on 11:27 pm
Awesome, saved me a headache!
October 13th, 2009 on 8:55 am
Thanks.Saved my precious time.
November 2nd, 2009 on 7:32 am
for your help. Spared me some digging.
March 10th, 2010 on 10:06 am
Thanks dude
July 20th, 2010 on 10:59 pm
I tried doing this, but the button text doesn’t update still
I want to try to change the text value from “start” to “stop” toggle when someone presses it like the stop watch application that came w/ the iphone.
Any hint on why that is the case?
July 21st, 2010 on 1:05 am
The possible control states are:
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
UIControlStateApplication
UIControlStateReserved
These are the possible values that you could have a different appearance for. For what you’re talking about, you would need to track the state yourself (running versus stopped) and change the characteristics of the UIControlStateNormal.