【问题标题】:iOS UIButton with multiple labels具有多个标签的 iOS UIButton
【发布时间】:2011-05-03 02:10:10
【问题描述】:

我有一个 UI 按钮,我想在其上放置两个标签,类似于单元格具有标题文本和详细信息文本的方式。

我希望按钮的主文本具有较大的字体,并在其下方具有较小的详细文本。

这可能吗?我尝试在一个按钮上放置多行,但我需要为每行设置不同的文本大小,因此设置 titleLabel 的 lineBreakMode 和 numberOfLines 并不太奏效。

【问题讨论】:

    标签: ios uibutton uilabel


    【解决方案1】:

    这是我们最终使用的代码。 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
    

    【讨论】:

      【解决方案2】:

      我推荐的一个技巧是在 UILabels 上放置一个内部透明的 UIButton。我以前用过这个技巧,虽然它可能会在维护和 i18n 方面出现一些问题,但它就像一个魅力。

      这是使用上述建议的 5 分钟示例。

      如果有更多时间,您可以制作出更好的圆角标签。

      【讨论】:

      • 感谢您的建议,但这需要我为按钮创建一个带有背景的视图,并且理想情况下,我希望按钮上有两种不同的字体样式。
      • @Orangemako 当您使用@Gordon 建议时,为标签背景赋予不同的颜色。
      • 这将没有动画
      【解决方案3】:

      您应该能够向其中添加子视图。由于一切都是视图,因此一切都可能具有子视图。

      我会将它子类化并将标签放在子类中,然后您可以扩展文本和子文本的属性以更改它们的值。

      并不是说它可以 100% 起作用。但在我的头上。 UIView 可以有子视图

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2017-09-18
        • 2014-12-08
        • 1970-01-01
        相关资源
        最近更新 更多