Search code examples
swiftmacosnstextview

NSTextView's textViewDidChangeSelection not called when option-command-dragging


I have an NSTextView.

textViewDidChangeSelection is being called when I drag to change the selection or if I command-drag, or if I option-drag, but not when I option-command-drag.

Sometimes the log will output the following:

[Framework] Shared items array is empty
[Framework] No shared items can be accessed

Option-command-dragging of course does change the selection, so I'd like to be notified when an option-command drag happens.


Solution

  • The "willChangeSelectionFromCharacterRanges" documentation says that it is only called when the "stillSelecting" argument of setSelectedRange or setSelectedRanges is set to false. So I subclassed NSTextView to override that argument like this:

    class NeverStillSelectingTextView : NSTextView {
    
    override func setSelectedRanges(_ ranges: [NSValue], affinity: NSSelectionAffinity, stillSelecting stillSelectingFlag: Bool) {
        super.setSelectedRanges(ranges, affinity: affinity, stillSelecting: false)
    }
    
    override func setSelectedRange(_ charRange: NSRange, affinity: NSSelectionAffinity, stillSelecting stillSelectingFlag: Bool) {
        super.setSelectedRange(charRange, affinity: affinity, stillSelecting: false)
    }
    }
    

    And now willChangeSelectionFromCharacterRanges is always called when you command-option drag.