How to add CSS for HTML to NSAttributedString?

Since iOS 7 you can use NSAttributedString with HTML syntax:

NSURL *htmlString = [[NSBundle mainBundle]  URLForResource: @"string"     withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
                                                                                       options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                            documentAttributes:nil
                                                                                         error:nil];
textView.attributedText = stringWithHTMLAttributes; // attributedText field!

You have to add string.html to you project, and the content of the html can be like this:

<html>
  <head>
    <style type="text/css">
      body {
        font-size: 15px;
        font-family: Avenir, Arial, sans-serif;
        color: red;
      }
    </style>
  </head>
  <body>
    <p>This is the text</p>
  </body>
</html> 

From what I could test, you can change: color, font-family, font-weight, font-size, text-align, and use <b>, <strong>, <i>, <u>, <sup>, and <sub> tags.

Leave a Comment