5

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).

Cue
  • 2,952
  • 3
  • 33
  • 54
  • 1
    check [that](http://stackoverflow.com/questions/1347779/how-to-navigate-through-textfields-next-done-buttons#1351090) out, hope it will guide you. – JFS Mar 10 '17 at 21:28
  • Thank you JFS, sure I will read it. – Cue Mar 11 '17 at 09:06

1 Answers1

12

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().

Dave Weston
  • 6,527
  • 1
  • 29
  • 44
  • Thank you dave, I tried to put it in the tableView tableViewSelectionDidChange and I get this error: **NSWindow: -_oldFirstResponderBeforeBecoming is not a valid message outside of a responder's implementation of -becomeFirstResponder.** Maybe I have to put in another part of the code? – Cue Mar 11 '17 at 09:05
  • 2
    Apple says: "Use the NSWindow `makeFirstResponder:` method, not this method, to make an object the first responder. Never invoke this method directly.". – Willeke Mar 11 '17 at 13:46