I'm trying to add an underline to some text in my Swift app. This is the code I have currently:
let text = NSMutableAttributedString(string: self.currentHome.name)
let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]
text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text
But I get this error on the text.addAttributes
line:
NSString
is not identical toNSObject
How can I add an attribute contained in an enum to an NSMutableAttributedString in Swift?
Update for Swift 4 syntax:
Here's a full example of creating a
UILabel
with underlined text:Swift 2:
Swift allows you to pass an
Int
to a method that takes anNSNumber
, so you can make this a little cleaner by removing the conversion toNSNumber
:Note: This answer previously used
toRaw()
as used in the original question, but that is now incorrect astoRaw()
has been replaced by the propertyrawValue
as of Xcode 6.1.In Xcode 6.1, SDK iOS 8.1
toRaw()
has been replaced byrawValue
:Or Easier :
Turns out I needed the
toRaw()
method - this works:If you want an actual dashed line, you should OR | the raw values of both PatternDash and StyleSingle enums like below: