How to display Underlined Text in a Button on iOS?
Adding a screenshot for @Haider's answer.
Note: Only the text you highlight gets underlined, so you can underline just a specific range if you want.
I ended up underlining it in code anyway, just because I couldn't get Bold to work in conjunction with Underline for some reason. Could have been because of the font I was using, who knows.
@IBOutlet weak var underlineButton: UIButton! {
didSet {
let attrs = [
NSFontAttributeName : UIFont(name: "MyCustomFont-Bold", size: 19.0)!,
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
NSForegroundColorAttributeName : UIColor.orangeColor()
]
let attrString = NSMutableAttributedString(string: "Button text", attributes:attrs)
underlineButton.setAttributedTitle(attrString, forState: .Normal)
}
}
Swift 3.2
if let title = button.titleLabel?.text, title != "" {
let attributeString = NSMutableAttributedString(string: title)
attributeString.addAttribute(NSAttributedStringKey.underlineStyle, value: 1, range: NSMakeRange(0, title.count))
button.titleLabel?.attributedText = attributeString
}
Objective C
NSString *tem = self.myButton.titleLabel.text;
if (tem != nil && ![tem isEqualToString:@""]) {
NSMutableAttributedString *temString=[[NSMutableAttributedString alloc]initWithString:tem];
[temString addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:1]
range:(NSRange){0,[temString length]}];
self.myButton.titleLabel.attributedText = temString;
}
To do it in interface builder
- Click on button/label
- In Attributes inspector, change Title/Text to Attributed from plain
- Select the text which you want to show.
- Right click on it Goto Font->Underline