Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track selection range change for NSTextField (cocoa)

Does anyone have any idea how I can track NSTextField.currentEditor.selectedRange value changes for NSTextField?

There is this wonderful thing NSTextViewDidChangeSelectionNotification, it does exactly what I need, but it works only for NSTextView.

I've tried to play with KVC/KVO but I didn't get what I wanted. I assume I did something wrong.

I will try to explain what I need to achieve.

I have NSTextField, below I have a label where I want to put values from NSTextField.currentEditor.selectedRange of text selection above. In realtime, i.e. I want to update my label content continuously with selection length and start position from NSTextField.currentEditor.selectedRange while selecting area of text.

like image 596
Thiaramus Avatar asked Sep 06 '14 22:09

Thiaramus


1 Answers

As mentioned in this "retired" article, the "field editor" designates the current text field as its delegate. Since the field editor is an NSTextView instance, we can implement any NSTextViewDelegate method in our NSTextField subclass.

- (void)textViewDidChangeSelection:(NSNotification *)notification
{
  NSRange selection = self.currentEditor.selectedRange;
  NSLog(@"selection = (location: %lu, length: %lu)", selection.location, selection.length);
}

Enjoy! ✌️

like image 82
aleclarson Avatar answered Oct 31 '22 13:10

aleclarson