我正在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时,这可以很好地显示passFieldalert.accessoryView = passField。但是我想在同一个对话框中显示两个字段。如您所见,我已经尝试了NSStackView(和其他),但是我还没有找到同时显示这两个元素的解决方案。

最佳答案

希望能帮到您...

您可以使用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

这是我的结果:

my result

08-15 20:51