I have UIButton. In interface builder I set its title to be 'Attributed'. How can I make its title to be underlined from code in Swift?
@IBOutlet weak var myBtn: UIButton!
I created a function called on the touchUpInside event of this button:
var attributedString = NSMutableAttributedString(string:"new text")
var attrs = [
NSFontAttributeName : UIFont.systemFontOfSize(19.0),
NSForegroundColorAttributeName : UIColor.redColor()
]
var gString = NSMutableAttributedString(string:"g", attributes:attrs)
attributedString.appendAttributedString(gString)
myBtn.titleLabel?.attributedText = attributedString;
But still no result. Also I need to know how to access the underline attribute. Text, size and color stay the same.
This is my solution. And to be honest you probably need this more than one place, so let's create an extension. This is swift 5.0 Cheers :)
And you can use it like this.
For swift 5
Based on some of previous answers I decide to make a class that can be easy implemented into your apps
Swift 4
From code I call it on such a way
button.setTitle(author, for: .normal)
Here you can add an underline and bold face too. You can just add an extention in your swift class file
Here is the extention (Swift 4 updated)
}
You can use it like this:
and the Result will be display like this
Here is done on the storyboard. (Xcode 9.1)
May not be the best approach but I made an example to use it with a separated class and make only a
one line
call to get the text.Here is my class:
Usage
let attributedString = AttributedTexts.set(string: "Skip", color: .white, type: .underlined, size: 19.0)
Best regards