I’m looking for a reliable technique to do simple string formatting(bold, italic,…) in a NSTextView. The text parsing is almost done with regex, but now I need to apply font trait and also change the size.
Some code snippets on how I make a text bold
[[textView textStorage] beginEditing];
[[textView textStorage] applyFontTraits:NSFontBoldTrait range:range];
[[textView textStorage] endEditing];
This and also the size changes with
[[textView textStorage] beginEditing];
NSFont* font = [[textView textStorage] attribute:NSFontAttributeName atIndex:range.location effectiveRange:nil];
NSFont* newFont = [NSFont fontWithName:[font familyName]
size:[font pointSize] + size];
[[textView textStorage] addAttribute:NSFontAttributeName
value:newFont
range:range];
[[textView textStorage] endEditing];
works fine. The only problem I have now is that in some cases, when I type new characters, those characters are bold or italic by default, even though I don’t apply the properties to them.
Do I have to reset something with the setTypingAttributes of the NSTextView or do I simply miss something here?
I think you are right with the approach to set
typingAttributes. Reference for-setTypingAttributes:saysThat seems to apply in your case.
I don’t know if the described behaviour is only correct for WYSIWYG editors like TextEdit. You seem to work on something that is similar in behaviour to an editor with syntax highlighting. There you never really want to change text attributes manually, but rather on structure from a grammar. It probably doesn’t fit in that case, and you should reset
typingAttributesor set it according to parsing up to there.