【发布时间】:2011-03-26 12:49:48
【问题描述】:
文本来自数据库。我想将它用于按钮并在按钮的文本下划线。我该怎么做?
【问题讨论】:
-
这里是如何在故事板(XCode 6)中做同样的事情。 stackoverflow.com/a/26930512/309046
标签: iphone objective-c cocoa-touch ios4
文本来自数据库。我想将它用于按钮并在按钮的文本下划线。我该怎么做?
【问题讨论】:
标签: iphone objective-c cocoa-touch ios4
在 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];
【讨论】:
为此,您可以继承 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];
}
【讨论】:
在 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)
}
}
【讨论】:
为了使这更简单(这是一个常见的要求),我构建了一个简单的 UIButton 子类,称为 BVUnderlineButton,您可以将其直接放入您的项目中。
它位于 Github 上,地址为 https://github.com/benvium/BVUnderlineButton(MIT 许可证)。
您可以在 XIB / Storyboard 中使用它或直接通过代码使用它。
【讨论】: