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