Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set first responder for NSTextView in Swift?

Edit: in a macOS project

I have a simple ViewController which I display as popover on a status item menu app.

I change the text of the view text with a NSTableView, depending of which item is clicked. The code I use is similar to this one:

mainTextField.insertText(newStr, replacementRange: theRange)

(I use insertText for the purpose to have the change recorded in undo manager)

Then I highlight the text:

// create the new NSRange
let range = NSRange(location: startRange, length: newStrLength)

// select the range in field
mainTextField.selectedRange = range

All work fine, except that the text is highlighted but with a light grey instead of the usual sky blue, indicating that the control is not the first responder. And when I click on the field the selection disappear.

Actually I would like that the NSTextView becomes first responder so I can directly copy the selected text.

Edit: if I press Tab key on the keyboard I got the textView to become first responder (and the grey selection becomes standard sky blue).

like image 769
Cue Avatar asked Dec 19 '22 09:12

Cue


1 Answers

Corrected Answer

In AppKit, you need:

if mainTextField.acceptsFirstResponder {
    mainTextField.window?.makeFirstResponder(mainTextField)
}

In this case, it's probably safe to not check acceptsFirstResponder, but it doesn't hurt either.

Original Answer (UIKit)

You need to call mainTextField.becomeFirstResponder().

like image 105
Dave Weston Avatar answered Jan 08 '23 19:01

Dave Weston