Search code examples
cocoanstextview

In a Cocoa Application for macOS, is it possible to get notified during a selection change and not only at the end of the change?


I would like to track the selection of a NSTextView continuously, but I only succeed to get the change when the selection finishes changing using :

- (void)textViewDidChangeSelection:(NSNotification *)notification {

}

Is there a way to track selection changes continuously ? Any help is greatly appreciated. Thanks


Solution

  • I succeeded to solve the issue by subclassing NSTextView and overriding the following method:

    -(void)setSelectedRanges:(NSArray<NSValue *> *)selectedRanges affinity:(NSSelectionAffinity)affinity stillSelecting:(BOOL)stillSelecting {
    
        [super setSelectedRanges:selectedRanges affinity:affinity stillSelecting:stillSelecting];
    
        if (stillSelecting && [self delegate] && [[self delegate] respondsToSelector:@selector(textViewDidChangeSelection:)]) {
            NSNotification *note = [[NSNotification alloc] initWithName:@"TextViewSelectionIsChangingNotification" object:self userInfo:nil];
            [[self delegate] textViewDidChangeSelection:note];
        }
    
    }
    

    This seems to me a good solution, it works well. Thanks.