Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS for HTML to NSAttributedString?

I am trying to load an HTML file via NSAttributedString to display it in a UITextView.

So, how can I apply CSS to the text view's content?

like image 478
Karan Alangat Avatar asked Feb 28 '14 09:02

Karan Alangat


1 Answers

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.

like image 81
André Rodrigues Avatar answered Nov 06 '22 04:11

André Rodrigues