How to make an underlined text in UILabel?

I am using Xcode 9 and iOS 11. To make the UILabel with an underline beneath it. You can use both 1. Using code 2. Using xib

Using code:

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

Using Xib: enter image description here

enter image description here

enter image description here

enter image description here

We can also use for button too.


Objective-C

iOS 6.0 > version

UILabel supports NSAttributedString

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

Swift

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

Definition :

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

Parameters List:

name : A string specifying the attribute name. Attribute keys can be supplied by another framework or can be custom ones you define. For information about where to find the system-supplied attribute keys, see the overview section in NSAttributedString Class Reference.

value : The attribute value associated with name.

aRange : The range of characters to which the specified attribute/value pair applies.

Now use like this:

yourLabel.attributedText = [attributeString copy];

iOS 5.1.1 < version

You needs 3 party attributed Label to display attributed text:

1) Refer TTTAttributedLabel link. Its best third party attributed Label to display attributed text.

2) refer OHAttributedLabel for third party attributed Label