Search code examples
swiftmacosnstextfieldfirst-respondernspopover

Force NSSearchField to Begin Editing When It Becomes First Responder


I have an NSSearchField in an NSPopover. This popover is opened when an NSStatusBar item is clicked.

In my NSPopover's view controller's viewWillAppear(), I call self.view.window?.makeFirstResponder(searchField) on my NSSearchField. I want this search field to be ready to edit when the popover is presented. By ready to edit, I mean the user will not have to click inside the NSSearchField to begin typing.

At this point, my implementation doesn't always work. Sometimes, it functions, and the popover opens with the search field ready, cursor blinking. Most of the time, however, especially if I'm editing text in a different application when I open the popover, the NSSearchField has to be clicked on to be edited.

I've subclassed the search field and overridden its becomeFirstResponder() method, and I can confirm it gets called every time.

How come I can't "steal" the right to edit my search field from other applications when the field becomes the first responder? Is this even possible?


Solution

  • It turns out the key was bringing my application to the forefront.

    I was able to give my application the system's focus by calling NSApplication.sharedApplication().activateIgnoringOtherApps(true). My NSSearchField, which was already becoming the first responder, can now directly be edited.