Mark
Mark

Reputation: 6977

How to clear NSTextView selection without it becoming first responder?

I have a basic Cocoa app with a number of NSTextViews. When a text view loses focus (i.e. resigns its first responder status), I'd like to clear its selection.

My strategy was to extend NSTextView and override resignFirstResponder():

override func resignFirstResponder() -> Bool {

    // Both result in the text view becoming first responder again:
    clearSelection(nil)
    setSelectedRange(NSRange(location: 0, length: 0))

    return super.resignFirstResponder()
}

The problem is that calling clearSelection() and setSelectedRange() both cause the text view to become first responder again.

Is there a way to clear the selection without it becoming the first responder?

I tried to also override acceptsFirstResponder and temporarily return false, but that didn't work either.

Upvotes: 3

Views: 608

Answers (1)

duan
duan

Reputation: 8885

Met the same issue today and found the solution

You can do setSelectedRange in NSTextView's delegate method textDidEndEditing and it wouldn't cause NSTextView become first responder.

class TextView: NSTextView {
    init() {
        self.delegate = self
        ....
    }
    ....
}

extension TextView: NSTextViewDelegate {
    public func textDidEndEditing(_ notification: Notification) {
        setSelectedRange(NSMakeRange(string.count, 0))
    }
}

Upvotes: 1

Related Questions