6

I am trying to use NSMutableAttributedString with dotted underline below is my code but none of the Patterns seem to work am I missing something ?

var str : NSMutableAttributedString = NSMutableAttributedString(string: "HelloWorld")
        str.addAttribute(NSUnderlineStyleAttributeName  , value: NSNumber(integer:(NSUnderlineStyle.PatternDot).rawValue), range: NSMakeRange(0, str.length))
Rajiv Patil
  • 61
  • 1
  • 2

1 Answers1

20

You have to do it like this:

Xcode 10 • Swift 4.2 or later

yourLabel.attributedText = NSAttributedString(string: "Hello World !!!", attributes: [.underlineStyle: NSUnderlineStyle.patternDot.union(.single).rawValue])

Note: for older Swift syntax check edit history

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • I had to do this in Swifth "uStyle = NSUnderlineStyle(rawValue: NSUnderlineStyle.PatternDot.rawValue | NSUnderlineStyle.StyleSingle.rawValue)" - I had a hard time figuring out how to "or" the two values :-) – David H Feb 13 '16 at 22:24
  • 1
    @DavidH it works for me as it is using Swift 2.1.1 https://www.dropbox.com/s/xio2279u5if7oqk/Screen%20Shot%202016-02-13%20at%2020.35.28.png?dl=1 – Leo Dabus Feb 13 '16 at 22:34
  • 1
    I'm curious why `rawValue` is necessary here. – bpedit Oct 25 '21 at 21:26
  • rawValue is actually what the dictionary wants `[.underlineStyle: 1]` works whereas `[.underlineStyle: .single]` does not – Magoo Mar 09 '22 at 12:58