vignesh kumar
vignesh kumar

Reputation: 2330

Setting the font of titleLabel of UIButton changes the textColor to default one?

I am now developing the application for ios 6 . It is a kind of form designing application where I found that if we change the titlelabel.textColor some point in the application then if we change the font then the textColor changes to the default one at the allocation time. I checked this like below

I drag a sample button to my sample viewcontroller and create an IBOutlet property named myButton in viewcontroller.h file in -viewDidLoad

[myButton.titleLabel setTextColor:[UIColor redColor]];

and in button action I did like below

- (IBAction)btnLoginClicke:(UIButton *)sender {
   [myButton.titleLabel setFont:[UIFont fontWithName:@"Arial" size:18]];

below are my before and after button click action screenshots

enter image description here

enter image description here

Upvotes: 1

Views: 2228

Answers (2)

tanz
tanz

Reputation: 2547

If you set the color of your UIButton title using:

[myButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

the color information won't be lost when you assign a new font.

I assume this is because the UIButton class internally setup the colour of the textLabel based on the different colours you had setup using setTitleColor (or the storyboard) for the different UIButton states. Changing directly the colour of the textLabel won't change the colour the UIButton has stored for each of these states, and they will be reapplied every time the UIButton needs to redraw itself. This is what happens when you setup the new font - the UIButton has to redraw itself but it will do it using the color setup via setTitleColor:forState:.

Upvotes: 1

Balram Tiwari
Balram Tiwari

Reputation: 5667

If you are going to keep all the buttons in your application with similar color, then better go for the global appearance settings. Then you need not have to worry about the button title color at all the places.

Put these lines in your appDelegate in the didFinishLaunchWithOptions method.

[[UIButton appearance] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[[UIButton appearance] setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];

Hope that helps.

Upvotes: 5

Related Questions