Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIButton with multiple labels

I have a UI button that I'd like to put two labels on it, similar to how a cell has a title text and detail text.

I'd like the button to have a larger font for the main text, and have smaller detail text under that.

Is this possible? I've tried to put multiple lines on a button, but I need to have different text sizes for each line, so setting the lineBreakMode and numberOfLines of the titleLabel doesn't really quite work.

like image 569
orangemako Avatar asked May 03 '11 02:05

orangemako


2 Answers

Here's the code we finally used. Assistance from John Wang.

Thanks to everyone for the suggestions!

// Formats a label to add to a button.  Supports multiline buttons
// Parameters:
// button - the button to add the label to
// height - height of the label.  usual value is 44
// offset - the offset from the top of the button
// labelText - the text for the label
// color - color of the text
// formatAsBold - YES = bold NO = normal weight
// tagNumber - tag for the label

- (void) formatLabelForButton: (UIButton *) button withHeight: (double) height andVerticalOffset: (double) offset andText: (NSString *) labelText withFontSize: (double) fontSize withFontColor: (UIColor *) color andBoldFont:(BOOL) formatAsBold withTag: (NSInteger) tagNumber {

    // Get width of button
    double buttonWidth= button.frame.size.width;

    // Initialize buttonLabel
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, offset, buttonWidth, height)];

    // Set font size and weight of label
    if (formatAsBold) {
        buttonLabel.font = [UIFont boldSystemFontOfSize:fontSize];
    }
    else {
        buttonLabel.font = [UIFont systemFontOfSize:fontSize];
    }

    // set font color of label
    buttonLabel.textColor = color;

    // Set background color, text, tag, and font
    buttonLabel.backgroundColor = [UIColor clearColor];
    buttonLabel.text = labelText;
    buttonLabel.tag = tagNumber;

    // Center label
    buttonLabel.textAlignment = UITextAlignmentCenter;

    // Add label to button
    [button addSubview:buttonLabel];

    [buttonLabel autorelease];
} // End formatLabelForButton
like image 163
orangemako Avatar answered Oct 13 '22 12:10

orangemako


A trick I would recommend is putting a UIButton with a transparent interior on top of UILabels. I've used this trick before and, although it may present some problems in terms of maintenance and i18n, it works like a charm.

Here is a 5 minutes sample using the suggestion above. Label behind button

Given more time, you can make a better label with round corners.

like image 35
G Gordon Worley III Avatar answered Oct 13 '22 13:10

G Gordon Worley III