Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton titleLabel not displaying

I have seen a bunch of similar questions, but noone got the answer I am looking for. When I use this code to make a UIButton and set it's titleLabel, the UIButton appear, but the titleLabel won't appear.

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[button setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
button.titleLabel.text = @"Title";
button.titleLabel.font = [UIFont fontWithName:@"System-Bold" size:25.0f];
[self.view addSubview:button];

This code displays the button, but not the titleView, it's title. Why can that be? I am developing for iOS 6 and higher.

NOTE 1: I am not looking for an option like this:

[button setTitle:@"Title" forState:UIControlStateNormal];

Because I have to use the titleLabel to set it's font and fontSize.

NOTE 2: I can't create a UILabel and add it as a subView of the button. Since the button is later animating.

like image 966
Peter Avatar asked May 20 '13 19:05

Peter


2 Answers

You always need to specify ControlState when updating button's title! There are four possible values for UIButtons:

UIControlStateNormal UIControlStateHighlighted UIControlStateDisabled UIControlStateSelected 

so for example:

[button setTitle:@"Title" forState:UIControlStateNormal]; 

and then you can set custom settings for titleLabel:

[button.titleLabel setFont:[UIFont fontWithName:@"Zapfino" size:20.0]]; [button.titleLabel setTextColor:[UIColor blueColor]]; 
like image 116
mdziadkowiec Avatar answered Sep 21 '22 02:09

mdziadkowiec


[button setTitle:@"Title" forState:UIControlStateNormal];

Is the correct way to set the title string.

titleLabel is used to set the font and color.

like image 31
andrew lattis Avatar answered Sep 21 '22 02:09

andrew lattis