简体   繁体   English

Swift:如何在 NSAlert 中制作 NSTextField 第一响应者

[英]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.模态框上有一个 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.我也无法让 becomeFirstResponder 工作。

UPDATE: I'm getting the error: ERROR: Setting as the first responder for window, but it is in a different window ((null)).更新:我收到错误:错误:设置为 window 的第一响应者,但它位于不同的 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.所以我明白为什么,但不知道如何解决。

Instead of makeFirstResponder, use this:而不是 makeFirstResponder,使用这个:

alert.window.initialFirstResponder = passField

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM