0

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?

jsd
  • 7,673
  • 5
  • 27
  • 47

2 Answers2

1

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.

jsd
  • 7,673
  • 5
  • 27
  • 47
  • You really should look at WebKit. Apple uses it for far more than you might imagine. What you are exploring is leftover from the days before WebKit. – uchuugaka May 09 '14 at 17:30
  • webkit would be total overkill for this particular case. we're talking 3-4 lines of text with the occasional or tag. – jsd May 09 '14 at 20:14
  • That was never noted. In that case NSTextView might also be fairly heavy weight. NSAttributedString is doing the work here really. – uchuugaka May 10 '14 at 01:40
1

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)
}
iHTCboy
  • 2,715
  • 21
  • 20