Search code examples
iphoneobjective-cuibuttonfont-sizeline-breaks

Title and subtitle with different fontsize for UIButton


I'd need a UIButton to display two lines of text, where the first one acts as a title and the second as some kind of subtitle, so it should be of a smaller font size. By now my button has two lines, custom font, and the content for the title/subtitle come from a UILabel each.

UIFont *displayFont = [UIFont fontWithName:@"Chalkboard" size:15];
NSString *buttonLabel;
UILabel *headline = [[UILabel alloc] init];
headline.text = @"This is the title";
UILabel *subtitle = [[UILabel alloc] init];
subtitle.text = @"this is the sub";

buttonLabel = [NSString stringWithFormat:@"%@\n%@", headline.text, subtitle.text];
[openDetail.titleLabel setLineBreakMode:UILineBreakModeWordWrap];
[openDetail setTitle:buttonLabel forState:UIControlStateNormal];
[openDetail.titleLabel setTextAlignment:UITextAlignmentCenter];
openDetail.titleLabel.font = displayFont;

I tried to set the Labels themselves to displayFont, so I could make a second UIFont, making the subtitle of it. Unfortunately the button label won't be of this font, if I keep the rest as shown above, but will switch back to Arial, I think it is, and didn't change the font size at all.

Any idea how I could achieve a smaller font size in the second line?

Side question for the font: I added Chalkboard.ttc to my Resources and added it as an entry in my info.plist as "Fonts provided by application". Still, if I try to set the font in IB, I'll get another font shown (very similar to Helvetica). Do I really have to set every buttons font programmatically now?


Solution

  • Try this

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(20 , 13, 200, 85)];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, 185, 30)];
    [title setBackgroundColor:[UIColor clearColor]];
    [title setFont:[UIFont fontWithName:@"Chalkboard" size:14]];
    [title setFont:[UIFont boldSystemFontOfSize:18]];
    title.text=@"This is the title";
    [title setTextColor:[UIColor blackColor]];
    [btn    addSubview:title];
    
    UILabel *subtitle = [[UILabel alloc]initWithFrame:CGRectMake(8, 20, 185, 30)];
    [subtitle setBackgroundColor:[UIColor clearColor]];
    [subtitle setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    subtitle.text=@"This is the sub";
    [subtitle setTextColor:[UIColor blackColor]];
    [btn    addSubview:subtitle];
    
    [title  release];
    [subtitle release];
    
    [self.view addSubview:btn];