How to code Swift and display a NSAlert?

I want to do as my question states. I've copied code on the subject and pasted it to playground, but each time, after the paste, xcode/playground locks up xcode which requires a reboot. I'm running the latest version of xCode and OS XI, and 've copied several versions of this,. All lock up xcode. The lastest attempt follows:


func dialogOKCancel(question: String, text: String) -> Bool {

let myPopup: NSAlert = NSAlert()

myPopup.messageText = question

myPopup.informativeText = text

myPopup.alertStyle = NSAlertStyle.warning

myPopup.addButton(withTitle: "OK")

myPopup.addButton(withTitle: "Cancel")

return myPopup.runModal() == NSAlertFirstButtonReturn

}


I plan to alert the application users of an input error, so they can correct it. In this mode, I'll delete the line to show the Cancel button.


What do I need to do to make this work?

Accepted Reply

Here is an example that works (tested in playGround), Swift 2.2


func errorReadingResults(question: String, text: String) -> Bool {


let alert = NSAlert()

alert.messageText = question

alert.informativeText = text

alert.addButtonWithTitle("OK")

alert.addButtonWithTitle("Cancel")

alert.alertStyle = .WarningAlertStyle

return alert.runModal() == NSAlertFirstButtonReturn

}


let x = errorReadingResults("Error.", text: "Impossible")


Did you copy this in a clean playground ? Or after some existing code, where maybe the problem is.

Replies

>In this mode, I'll delete the line to show the Cancel button.


Why? It's normal UI to include it...that may be your issue.


Otherwise, if you simply want a popup alert with an input field and one 'submit' button, see:


h t t p s : / / peterwitham.com/swift/intermediate/alert-with-user-entry/

Here is an example that works (tested in playGround), Swift 2.2


func errorReadingResults(question: String, text: String) -> Bool {


let alert = NSAlert()

alert.messageText = question

alert.informativeText = text

alert.addButtonWithTitle("OK")

alert.addButtonWithTitle("Cancel")

alert.alertStyle = .WarningAlertStyle

return alert.runModal() == NSAlertFirstButtonReturn

}


let x = errorReadingResults("Error.", text: "Impossible")


Did you copy this in a clean playground ? Or after some existing code, where maybe the problem is.

I am a newbie here, first request. This is called-from and declared inside my viewcontroller class:

func NrangeAlert() {

let alert = NSAlert()

alert.messageText = "N out of range"

alert.informativeText = "use a number between 1 and 92"

alert.alertStyle = .warning

alert.addButton(withTitle: "OK")

alert.runModal()

print("Select a number between 1 and 92")

}

but fails to show the alert. It compiles. XCode Version 11.3.1 (11C504) It successfully prints to the debugger area.

What am I missing?