【问题标题】:Multiple NSTextField in an NSAlert - MacOSNSAlert 中的多个 NSTextField - MacOS
【发布时间】:2018-04-21 21:39:35
【问题描述】:

我正在 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 ("", "")
        }
    }

当我执行alert.accessoryView = passField 时,这可以很好地显示unameFieldpassField。但我想在同一个对话框中显示这两个字段。如您所见,我已经尝试过 NSStackView (和其他),但我还没有找到显示这两个元素的解决方案。

【问题讨论】:

    标签: swift nsview nsalert


    【解决方案1】:

    希望能帮到你……

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 2015-03-08
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多