-1

In my MacOS app, there is an NSSearchField in the Toolbar. I want to enable users to focus it by pressing CMD+F (the same behavior that is used in many of Apple’s apps). I created an NSMenuItem with a key equivalent of CMD+F – it calls the following function, which is supposed to make the NSSearchField first responder.

@IBAction func focusFilter(_ sender: NSMenuItem) {
    self.view.window?.toolbar?.items.first(where: { (item) -> Bool in
        return item.itemIdentifier.rawValue == "Search"
    })?.view?.becomeFirstResponder()
}

When pressing CMD+F it seems as if the NSSearchField becomes the first responder for a very short time (the title starts moving to the left), but then it loses focus before the Focus Ring appears (the NSSearchField does not refuse first responder).

I also tried using the NSToolbarItem’s menuFormRepresentation.view, with the same result.

How can I make an NSToolbarItem become first responder? Any help is appreciated!

chl
  • 380
  • 3
  • 18
  • 1
    From the documentation of `becomeFirstResponder`: "Use the NSWindow makeFirstResponder: method, not this method, to make an object the first responder. Never invoke this method directly.". – Willeke Jul 29 '18 at 14:14
  • @Willeke Ugh, so simple! I am relatively new to macOS programming, so sometimes I miss the obvious stuff. Thanks so much for pointing me in the right direction! – chl Jul 29 '18 at 14:48

1 Answers1

0

As mentioned by @Willeke, the right solution is not the use becomeFirstResponder, but to use NSWindow makeFirstResponder: instead. It works fine with this code:

@IBAction func focusFilter(_ sender: NSMenuItem) {
    if let searchItem = self.view.window?.toolbar?.items.first(where: { (item) -> Bool in
        return item.itemIdentifier.rawValue == "Search"
    }) {
        self.view.window?.makeFirstResponder(searchItem.view)
    }
}
chl
  • 380
  • 3
  • 18