Search code examples
swiftnsattributedstring

how to add specific attributes to a NSAttributedString in Swift


This is a simple question but is erroring in several places so I think there's something I'm just not getting (and it's a coworkers app who's no longer here). I am migrating an Objective-C app to Swift and am having some problems with NSAttributedString.

There is a note.body which gets set to an NSMutableAttributedString and each note has a .frags array of strings which are the sections that we want to add the attributes to.

I have:

var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(9.0)]
var gString = NSMutableAttributedString(string:note.body, attributes:attrs)  // say note.body="birds and bees"

let firstAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(), NSBackgroundColorAttributeName: UIColor.yellowColor(), NSUnderlineStyleAttributeName: 1]
for (val) in note.frags {  // say note.frags=["bees"]
  let tmpVal = val
  gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: gString.string.rangeOfString(tmpVal))
}

How would I add the first attributes?

The error I get is:

Cannot invoke 'addAttribute' with an argument list of type '(String, value: Int, range: Range?)'


Solution

  • The problem is you are calling the method with a Range? parameter when a NSRange is expected.

    To make sure you get a NSRange, you'll need to convert the String to NSString first.

    This code works on a Playground:

    for val in note.frags {  // say note.frags=["bees"]
        let range: NSRange = NSString(string: gString.string).rangeOfString(val)
        gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: range)
    }