1
votes

I have a window with some NSTextFields. When I click in one and edit the value and press return, I want the focus to go back to what it was before. I don't want the blue ring around the text field and I don't want further keystrokes going to that text field. I would have thought this would happen automatically.

I tried these, and none of them work

 sender.resignFirstResponder()

 sender.window?.makeFirstResponder(nil)

 InspectorWindowController.window?.makeFirstResponder(nil)

 AnotherWindowController.window?.becomeFirstResponder()

I'm doing these at the end of my IBAction associated with the text field. Maybe I have to do it from somewhere else?

Thanks

2
What was the focus before?Willeke

2 Answers

1
votes

I figured this out. I guess the sent action is happening on another thread. So you have to call makeFirstResponder using Dispatch async.

DispatchQueue.main.async { //omg
    sender.window?.makeFirstResponder(nil)
}
0
votes

I needed to dismiss first responder in my SwiftUI macOS app and here what I found working in a way I need:

    func controlTextDidEndEditing(_ obj: Notification) {
      DispatchQueue.main.async {
        guard let window = self.textField.window else {
          return
        }
        // https://stackguides.com/questions/5999148/how-to-determine-whether-an-nssearchfield-nstextfield-has-input-focus
        // We need to make sure that our text field is still first responder.
        guard let textView = window.firstResponder as? NSTextView,
              textView.delegate === self.textField else {
          return
        }
        
        window.makeFirstResponder(nil)
      }
    }