我在MacOS上使用Swift 4中的NSAlert组合了一个登录对话框。这是我到目前为止的代码:
func dialogOKCancel(question: String, text: String) -> (String, String) {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .warning
alert.addButton(withTitle: "Login")
alert.addButton(withTitle: "Cancel")
let unameField = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
let passField = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 24))
let stackViewer = NSStackView()
stackViewer.addSubview(unameField)
alert.accessoryView = stackViewer
let response: NSApplication.ModalResponse = alert.runModal()
if (response == NSApplication.ModalResponse.alertFirstButtonReturn) {
return (unameField.stringValue, passField.stringValue)
} else {
return ("", "")
}
}
当我执行unameField
时,这可以正常显示passField
或alert.accessoryView = passField
。但我想在同一个对话框中显示这两个字段。正如您所看到的,我已经尝试过NSStackView(以及其他),但我还没有找到显示这两个元素的解决方案。
答案 0 :(得分:4)
您可以使用NSStackView和addSubview 2项:unameField和passField。 但是你必须在NSStackView上为NSStackView和2项设置框架。
这是我的代码,你可以参考:
let unameField = NSTextField(frame: NSRect(x: 0, y: 2, width: 200, height: 24))
let passField = NSSecureTextField(frame: NSRect(x: 0, y: 28, width: 200, height: 24))
let stackViewer = NSStackView(frame: NSRect(x: 0, y: 0, width: 200, height: 58))
stackViewer.addSubview(unameField)
stackViewer.addSubview(passField)
alert.accessoryView = stackViewer
这是我的结果: