Search code examples
xcodemacoscustomizationnstextfieldnsnotifications

OSX NSTextField resets attributedStringValue when text is selected


I set attributedStringValue for NSTextField with highlighted words: enter image description here

but when i select text by cursor all highlighted words get usual style: enter image description here

I've tried following:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(controlTextDidSelected:) name:NSTextViewDidChangeSelectionNotification object:nil];

- (void)controlTextDidSelected:(NSNotification *)notification {
    self.attributedStringValue = _attrString;
}

But still not working while selecting.

How can i have highlighted words while text is selected? Thanks in advance.


Solution

  • I had the same issue. 2 things help me:
    1. set font for whole attributed string
    2. allow editing for text attributes. Please check code below:

    [self.yourTextField setAllowsEditingTextAttributes: YES];
    [attrString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, [stringValue length])];