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.
Thanks for posting your code, it wasn't clear that you knew how to create an attributed string at all.
This should work:
Swift 4 version:
Here you go, just tested it. (works in xCode 7 Beta at least)
if you are looking for a way to do this without inheritance -
swift 3/4/5
StoryBoard: If you want to Underline text from storyBoard.
Swift 5 / Xcode 11
Swift 4 / Xcode 9
Swift 3 / Xcode 8
@ShlomoKoppel answer in
Swift 4.2