iph*_*aaw 2 macos nstextfield nsalert becomefirstresponder swift
我有一个简单的登录对话框,要求输入密码。在模态上是一个 NSSecureTextField。我希望这是第一响应者,但我一直无法找到如何做到这一点?
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 ("")
}
}
Run Code Online (Sandbox Code Playgroud)
我也无法让 becomeFirstResponder 工作。
更新:我收到错误:错误:设置为窗口的第一响应者,但它在不同的窗口中((空))!当视图被释放时,这最终会崩溃。第一响应者将被设置为 nil。
所以我明白为什么,但只是不知道如何解决。
小智 8
而不是 makeFirstResponder,使用这个:
alert.window.initialFirstResponder = passField
Run Code Online (Sandbox Code Playgroud)