NSTextView and NSAttributedString

Gargoyle picture Gargoyle · Jul 16, 2013 · Viewed 11.5k times · Source

I'm trying to stick an attributed string into my NSTextView, but it's just showing as plain text, no attributes. I created my string like so:

    NSString *str = @"Parsing Directory Structure\n\n";

NSMutableAttributedString *attrstr = [[NSMutableAttributedString alloc] initWithString:str];
NSDictionary *attributes = @{
                             NSForegroundColorAttributeName : [NSColor blueColor],
                             NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:20.f]
                             };
[attrstr setAttributes:attributes range:NSRangeFromString(str)];

[[self.textView textStorage] appendAttributedString:attrstr];

and on the NSTextView (inside the scrolling view) I've got the "Allows Rich Text" box checked still, and the Editable box unchecked. I'm basically trying to use this like a console output window.

Answer

CRD picture CRD · Jul 16, 2013

NSMakeRangeFromString parses a textual representation of a range, it doesn't create a range which covers a string. As your text contains no integers it return the range {0, 0} - location and length both zero. So while your text is not styled.

Replace with NSMakeRange(0, str.length) and your code should work.