Search code examples
macoscocoaappkit

NSText applyFontTraits doesn't work on multiline NSTextView


I'm experiencing some problems when trying to change the font style of a part of the text inside an NSTextView widget to bold. The text runs across several lines. Here's my code:

[tv setString:@"\nTest Prog 1.0\n-Mac OS version -\nRelease date: 08.04.2015"];
NSMutableAttributedString *text = [tv textStorage];
[text applyFontTraits:NSBoldFontMask range:NSMakeRange(15,32)];

As you can see, I'm passing range 15 to 32 which means that the second line ("-Mac OS version-") should be printed bold. However, this is not what happens. Instead, I get this look:

Screenshot of bad behaviour

As you can see, the third line is also printed in bold but I don't understand why this happens. Am I doing something wrong here or is this a bug in Mac OS itself?

The behaviour is confirmed with 10.6 (my development system) and 10.10 Yosemite (my test system).

Any ideas?


Solution

  • The second parameter of NSMakeRange() is not the end index of the range, it's the length. You've specified a range starting at index 15 and running for 32 characters.

    Cocoa has bolded exactly the text you specified.