Search code examples
swiftnstextfieldfirst-responderbecomefirstresponder

makeFirstResponder: does not always take cursor


When I display my app with a keyboard shortcut or by tapping an icon in the status bar I set first responder. makeFirstResponder: always succeeds (returns true) with a not-nil window and a not-nil NSTextField. However it doesn't always 'take the cursor' (i.e. move the flashing | to the NSTextField).

For example,

  • display app - takes cursor ✓
  • tap outside app
  • display app again - does not take cursor (even though makeFirstResponder returns true).

Here's how I'm trying to do this:

//Find the key window. I don't think this is the problem because self.window produces the same results. 
var keyWindow:NSWindow = popover.contentViewController!.view.window!

for window in NSApplication.sharedApplication().windows{
    if (window.keyWindow){
        Swift.print("window \(window) is the key window")
        keyWindow = window
    }
}

//iFR is a variable that I use to keep track of which NSTextField I want to focus on. It's always a valid textField and most of the time (but not always) it's the only NSTextField in the view. 
if (initialFirstResponder != nil)
    {
        if keyWindow.makeFirstResponder(initialFirstResponder)
        {
            Swift.print("first responder success")
        }else
        {
            //Never happens:
            Swift.print("first responder FAIL")
        }

    }else
    {
         Swift.print("no initial firstResponder")
    }

Solution

  • I feel like I'm bludgeoning the responder chain into submission but,

    NSApp.activateIgnoringOtherApps(true)
    

    causes the cursor to always be captured (and asked nicely) to go where I want it to.