Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This works just fine to show either the unameField or passField when I do alert.accessoryView = passField. But I want to show both fields in the same dialog. As you can see I've experimented with NSStackView (and others), but I have not found a solution to show both elements.

like image 902
CorlinP Avatar asked Nov 09 '17 01:11

CorlinP


1 Answers

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

like image 55
Thuan Nguyen Avatar answered Oct 15 '22 07:10

Thuan Nguyen