How to make an underlined text in UILabel?

Dev*_*Dev 25 cocoa-touch text underline uilabel ios

如何制作带下划线的文字UILabel

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

我怎样才能做到这一点?

Par*_*iya 75

Objective-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]}];
Run Code Online (Sandbox Code Playgroud)

迅速

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

定义:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange
Run Code Online (Sandbox Code Playgroud)

Parameters List:

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

value:与name关联的属性值.

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

现在使用这样:

yourLabel.attributedText = [attributeString copy];
Run Code Online (Sandbox Code Playgroud)

iOS 5.1.1 <版本

你需要3 party attributed Label显示attributed text:

1)参考TTTAttributedLabel链接.它的最好的第三方attributed Labeldisplaytext.

2)将OHAttributedLabel引用给第三方attributed Label


Ani*_*pta 6

我正在使用Xcode 9和iOS11。要使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;
Run Code Online (Sandbox Code Playgroud)

使用Xib: 在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

我们也可以使用按钮。


Mic*_*ick 5

设计师之道 - 高度可定制的版本

我个人更喜欢尽可能地定制我的设计。有时,您会发现使用内置的下划线工具并不容易定制。

这是我如何做到的:

1首先,我为下划线创建了一个 UIView。然后,您可以在 IB 中或以编程方式选择背景颜色。约束是这里的关键。

创建您的下划线视图

2然后,您可以根据需要自定义下划线。例如,为了适应下划线的宽度以获得更好的视觉效果,在 Interface Builder 中创建一个到约束的出口连接

在此处输入图片说明

3然后,您可以轻松地以编程方式自定义下划线视图。例如在这里,为了给您一个想法,我们将使下划线比标题“面包”宽 20 像素:

var originalString: String = "Breads"
let myString: NSString = originalString as NSString
let size: CGSize = myString.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
self.widthUnderlineTitle.constant = size.width + 20
Run Code Online (Sandbox Code Playgroud)

Results:

在此处输入图片说明