2011-05-03 67 views
6

我有一個UI按鈕,我想在其上放置兩個標籤,類似於單元格具有標題文本和詳細文本的方式。具有多個標籤的iOS UIButton

我希望按鈕的主要文本具有較大的字體,並且具有較小的細節文本。

這可能嗎?我試圖在按鈕上放置多行,但是我需要爲每行添加不同的文本大小,因此設置titleLabel的lineBreakMode和numberOfLines並不十分有效。

回答

6

這裏是我們最終使用的代碼。 John Wang的協助。

感謝大家的建議!

// 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 
4

我推薦的一個技巧是在UILabels上放置一個帶有透明內部的UIButton。我之前使用過這個技巧,雖然它在維護和國際化方面可能會出現一些問題,但它的作用就像魅力。

以下是使用上述建議的5分鐘樣本。 Label behind button

給予更多時間,您可以製作更好的圓角標籤。

+0

感謝您的建議,但這需要我爲該按鈕創建一個背景,並且我希望在按鈕上有兩種不同的字體樣式。 – orangemako 2011-05-03 02:25:38

+0

@Orangemako當你使用@Gordon建議時,給標籤背景一個不同的顏色。 – 2011-05-03 03:20:53

1

你應該可以添加子視圖。由於一切都是視圖,所有事物都可能有子視圖。

我會繼承它並在其子類中放置標籤,然後可以擴展文本和子文本的屬性以更改它們的值。

不說它可以100%的工作。但我的頭頂。 UIView可以有SubViews