Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Rather than repeat the css you need across multiple files, if you are storing the files in your Assets folder then one option is to have a single file containing all the html before the body tag, which contains all the style information. You can then append the bytes, as shown in this example from my own code:

func loadHTMLData(section:String, page:Int) -> NSAttributedString? {
    var data = Data()
    if let asset = NSDataAsset(name: "htmlhead") {
        data.append(asset.data)
    }

    if let asset = NSDataAsset(name: "\(section)\(page)") {
        data.append(asset.data)
        do {
            let attr = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
            return attr
        }
        catch {
            // do something with error
            return nil
        }
    }
    else {
        return nil
    }
}

There's also nothing to stop you from splitting the files further if you wish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top