swiftmacosnstextfieldbecomefirstrespondernsalert

Swift: How to make NSTextField first responder in NSAlert


I have a simple login dialog that asks for a password. On the modal is a NSSecureTextField. I would like this to be the first responder but I haven't been able to find how to do this?

func loginDialog(question: String) -> String 
{
    let alert = NSAlert()
    alert.messageText = question
    alert.alertStyle = .warning
    alert.addButton(withTitle: "Login")
    alert.addButton(withTitle: "Cancel")

    let passField = NSSecureTextField(frame: NSRect(x: 0, y: 24, width: 250, height: 24))
    let stackViewer = NSStackView(frame: NSRect(x: 0, y: 0, width: 250, height: 50))

    stackViewer.addSubview(passField)

    alert.accessoryView = stackViewer

    //this doesn't do anything :-(
    alert.window.makeFirstResponder(passField)

    let x = alert.runModal()
    if (x == NSApplication.ModalResponse.alertFirstButtonReturn)
    {
        return (passField.stringValue)
    }
    else
    {
        return ("")
    }
}

I couldn't get becomeFirstResponder to work either.

UPDATE: I'm getting the error : ERROR: Setting as the first responder for window , but it is in a different window ((null))! This would eventually crash when the view is freed. The first responder will be set to nil.

So I understand why, but just not how to fix.


Solution

  • Instead of makeFirstResponder, use this:

    alert.window.initialFirstResponder = passField