jsd
jsd

Reputation: 7703

NSTextView displaying HTML via Cocoa Bindings

I've got a string with some simple HTML in it (mainly just and
tags). I'm displaying them in an NSTextView using Cocoa Bindings. Unfortunately the html just shows up inline, it doesn't actually change the formatting. Is there a way to do get the html to render using bindings? If not, how would you do it?

Upvotes: 0

Views: 1890

Answers (2)

iHTCboy
iHTCboy

Reputation: 2797

Swift 5:

let data = htmlString.data(using: .utf8)!
if let attributedString = NSAttributedString(html: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil) 
{
      textView.textStorage?.append(attributedString)
      textView.textColor = .labelColor
      textView.font = NSFont.systemFont(ofSize: 15)
}

Upvotes: 1

jsd
jsd

Reputation: 7703

Turns out it's fairly straightforward. The NSTextView bindings panel in Interface Builder has a "Value" section at the top, and the first choice is Attributed String. Just bind the Attributed String to an NSAttributedString property on your model object. You can create the attributed string from a normal string with html tags in it like so:

NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTML:data
                                        baseURL:nil
                             documentAttributes:nil];

I don't know how much HTML you can cram in there (maybe javascript doesn't work) but basic stuff like stylesheets seems to work fine.

Upvotes: 1

Related Questions