Add NSUnderlineStyle.PatternDash to NSAttributedString in Swift?

Undo picture Undo · Sep 1, 2014 · Viewed 14.8k times · Source

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 to NSObject

How can I add an attribute contained in an enum to an NSMutableAttributedString in Swift?

Answer

vacawama picture vacawama · Sep 2, 2014

Here's a full example of creating a UILabel with underlined text:

Swift 5:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.single.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

Swift 4:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

Swift 2:

Swift allows you to pass an Int to a method that takes an NSNumber, so you can make this a little cleaner by removing the conversion to NSNumber:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))

Note: This answer previously used toRaw() as used in the original question, but that is now incorrect as toRaw() has been replaced by the property rawValue as of Xcode 6.1.