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];

:

8 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...