Make NSToolbarItem become first responder

329 Views Asked by At

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!

1

There are 1 best solutions below

0
On

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