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.
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]];
[button setTitle:@"Title" forState:UIControlStateNormal];
Is the correct way to set the title string.
titleLabel is used to set the font and color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With