如何在UILabel中加下划线的文字?

时间:2012-10-29 13:01:49

标签: ios cocoa-touch text uilabel underline

如何在UILabel中添加带下划线的文字?

我尝试过制作高度 0.5f UILabel并将其放在文字下面。当我在 iPhone 4.3 iPhone 4.3模拟器中运行我的应用时,此行标签不可见,但在 iPhone 5.0模拟器中可见。为什么呢?

我该怎么做?

6 个答案:

答案 0 :(得分:75)

目标C

iOS 6.0>版本

UILabel支持NSAttributedString

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Hello Good Morning"];
[attributeString addAttribute:NSUnderlineStyleAttributeName
                        value:[NSNumber numberWithInt:1]
                        range:(NSRange){0,[attributeString length]}];

夫特

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Hello Good Morning")
attributeString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))

定义

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange

Parameters List:

name :指定属性名称的字符串。属性键可以由另一个框架提供,也可以是您定义的自定义键。有关在何处查找系统提供的属性键的信息,请参阅NSAttributedString类参考中的概述部分。

:与name关联的属性值。

aRange :指定属性/值对应用的字符范围。

现在使用这样:

yourLabel.attributedText = [attributeString copy];

iOS 5.1.1<版本

您需要3 party attributed Label才能显示attributed text

1)参考TTTAttributedLabel链接。最好的第三方attributed Labeldisplay归因于text

2)请参考OHAttributedLabel了解第三方attributed Label

答案 1 :(得分:5)

我正在使用Xcode 9和iOS 11。 使UILabel下方有下划线。 你可以使用两者  1.使用代码  2.使用xib

使用代码:

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"I am iOS Developer"];
[attributeString addAttribute:NSUnderlineStyleAttributeName
                        value:[NSNumber numberWithInt:1]
                        range:(NSRange){0,[attributeString length]}];
lblAttributed.attributedText = attributeString;

使用Xib: enter image description here

enter image description here

enter image description here

enter image description here

我们也可以使用按钮。

答案 2 :(得分:3)

看看TTTAttributedLabel。如果您被允许使用3d-party组件,只需将您的UILabel替换为您需要的TTTAttributedLabel(直接替换)。适用于iOS< 6.0!

答案 3 :(得分:2)

UILabel的快速扩展:

仍然需要改进,欢迎任何想法:

extension UILabel{

    func underLine(){    
        if let textUnwrapped = self.text{
            let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
            let underlineAttributedString = NSAttributedString(string: textUnwrapped, attributes: underlineAttribute)
            self.attributedText = underlineAttributedString   
        }   
    }
}

我现在能够想到的一个缺点是,每次文字发生变化时都需要调用它,并且没有实际的方法可以将其关闭......

答案 4 :(得分:0)

Swift 4.0

var attributeString = NSMutableAttributedString(string: "Hello Good Morning")
attributeString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: NSRange)

答案 5 :(得分:0)

雨燕5

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: yourLabel.text ?? "")
attributeString.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: NSMakeRange(0, attributeString.length))
yourLabel.attributedText = attributeString
相关问题