简体   繁体   中英

Multiple NSTextField in an NSAlert - MacOS

I am putting together a login dialog using an NSAlert in Swift 4 on MacOS. Here is the code I have so far:

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

Hope will help you ...

You can use NSStackView and addSubview 2 item : unameField and passField. But you must set frame for NSStackView and 2 item on NSStackView.

This is my code, you can refer:

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

And this is my result:

my result

My code: https://github.com/nhhthuanck/CustomizeNSAlertMacOS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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