objective-ccocoanstextfieldrichtext

NSAttrbutedText object output's a raw string instead of rich text in my NSTextField


I have an NSTextField in my XIB, and I created a NSAttributedString instance, and used initWithHTML:documentAttributes: with an NSData object of some html with bold and italic etc. I used setAttributedText and it outputs plain text of the object:

enter image description here

I am using PyObj-C bridge for my code, so here's my code:

html = """<p><b>Word</b> - English</p>
<p><i>Phonetics</i> - Noun</p>
<p><i>A love this word!</i></p>
<p>Definition - An abstraction</p>
"""
new_html = str.encode(html) # Turn html into byte code for NSData

# Make an NSData object with the html string in it
html = Cocoa.NSData.alloc().initWithBytes_length_(new_html, len(new_html))

# Make an instance of an Attributed String
attrString = Foundation.NSAttributedString.alloc().init()

# Instantiate attributed string with the NSData html string
definition = attrString.initWithHTML_documentAttributes_(html, None)
self.definitionField.setAttributedStringValue_(definition)

Am I doing something wrong? I've looked everywhere on the web, cant seem to find a forum post with my problem too.


Solution

  • The second argument of initWithHTML_documentAttributes_ is a pass-by-reference in-out argument in Objective-C. Because of this the Python version of this method returns a tuple of two values: the actual return value and the output version of the second argument.

    To get the behaviour you want use:

    
    definition, _ = Foundation.NSAttributedString.initWithHTML_documentAttributes_(html, objc.NULL)
    

    This also sets the second argument to objc.NULL instead of None to tell the method that your not interested in getting a dict with attributes.

    Some other notes: