【问题标题】:How Can I Underline the Button Text of UIButton?如何在 UIButton 的按钮文本下划线?
【发布时间】:2011-03-26 12:49:48
【问题描述】:

文本来自数据库。我想将它用于按钮并在按钮的文本下划线。我该怎么做?

【问题讨论】:

标签: iphone objective-c cocoa-touch ios4


【解决方案1】:

在 iOS 6 中,NSAttributedString 用于修改文本,您可以使用单个 UIButton 或 UILabel 对多色文本、字体、样式等使用“NSMutableAttributedString”。

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"The Underlined text"];

// making text property to underline text-
[titleString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];

// using text on button
[button setAttributedTitle: titleString forState:UIControlStateNormal];

【讨论】:

  • 我们可以把线调低吗?
【解决方案2】:

为此,您可以继承 UILabel 并覆盖其 -drawRect 方法,然后使用您自己的 UILabel 并在其上添加自定义类型的 UIButton

将 UILabel 中的 drawRect 方法设为

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBStrokeColor(context, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f);

    CGContextSetLineWidth(context, 1.0f);

    CGContextMoveToPoint(context, 0, self.bounds.size.height - 1);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height - 1);

    CGContextStrokePath(context);

    [super drawRect:rect]; 

}

【讨论】:

    【解决方案3】:

    在 Swift 3 中,以下扩展名可用于下划线:

    extension UIButton {
        func underlineButton(text: String) {
            let titleString = NSMutableAttributedString(string: text)
            titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, text.characters.count))
            self.setAttributedTitle(titleString, for: .normal)
        }
    } 
    

    【讨论】:

      【解决方案4】:

      为了使这更简单(这是一个常见的要求),我构建了一个简单的 UIButton 子类,称为 BVUnderlineButton,您可以将其直接放入您的项目中。

      它位于 Github 上,地址为 https://github.com/benvium/BVUnderlineButton(MIT 许可证)。

      您可以在 XIB / Storyboard 中使用它或直接通过代码使用它。

      【讨论】:

        猜你喜欢
        • 2011-02-07
        • 2016-03-13
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        • 2014-05-21
        • 2011-02-08
        • 1970-01-01
        • 2016-04-04
        相关资源
        最近更新 更多