Search code examples
htmliosswiftnsattributedstring

How do I edit the attributes of an NSAttributedString?


I want to be able to edit the HTML I get from my api request, changing the font and increasing among other things.

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    var dataString:String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
    dispatch_async(dispatch_get_main_queue()) {

        var attributedString:NSAttributedString = NSAttributedString(data: data, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!

        self.textView.attributedText =  attributedString
    }
}

Solution

  • To access the properties correctly you should be using an NSMutableAttributeString.

    Change your String instantiation to this:

    var attributedString: NSMutableAttributedString = NSMutableAttributedString(data: data, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
    

    And add an attribute like so:

    mutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Avenir", size: 18.0)!, range: NSRange(location:2,length:4))
    

    This is just an example, you can create your own attributes to suit your needs.