Create an NSAlert with Swift
beginSheetModalForWindow:modalDelegate
is deprecated in OS X 10.10 Yosemite.
Swift 2
func dialogOKCancel(question: String, text: String) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.WarningAlertStyle
alert.addButtonWithTitle("OK")
alert.addButtonWithTitle("Cancel")
let res = alert.runModal()
if res == NSAlertFirstButtonReturn {
return true
}
return false
}
let answer = dialogOKCancel("Ok?", text: "Choose your answer.")
This returns true
or false
according to the user's choice.
NSAlertFirstButtonReturn
represents the first button added to the dialog, here the "OK" one.
Swift 3
func dialogOKCancel(question: String, text: String) -> Bool {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert.runModal() == NSAlertFirstButtonReturn
}
let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")
Swift 4
We now use enums for the alert's style and the button selection.
func dialogOKCancel(question: String, text: String) -> Bool {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert.runModal() == .alertFirstButtonReturn
}
let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")
How do I write an NSAlert in latest swift?
You should run your code from viewDidAppear
because your view controller has not created a window object in viewDidLoad
.
override func viewDidAppear() {
super.viewDidAppear()
alertUser()
}
When creating an NSAlert in Objective C, will I need to release the NSAlert?
If you have ARC enabled (which has been the default for new projects for years), then you don't need to release the NSAlert
. In fact the code will not compile if you try to, because you are not allowed to send the release
message when ARC is enabled.
If you have ARC disabled, then yes, you should [alert release]
after you [alert runModal]
. You need to release
because you became an owner of it when you sent the alloc
message.
Read more in “Memory-Management Rules” in the Cocoa Core Competencies guide.
If your project already contains Swift code, then there is no particular reason to use Objective-C instead of Swift to create this alert.
If your project doesn't already contain Swift code, then adding your first Swift code to the project may increase your compile times more than you want. Objective-C typically compiles much faster than Swift.
NSAlert destructive button
Set the property hasDestructiveAction
of the button to true
. This property is new in Big Sur.
Source: AppKit Release Notes for macOS Big Sur 11
Swift: How to make NSTextField first responder in NSAlert
Instead of makeFirstResponder, use this:
alert.window.initialFirstResponder = passField
How to ensure NSAlert pop up on window top?
I found an answer to my own question:
alert.window.level = .floating
This works.
Related Topics
Programmatically Screenshot | Swift 3, Macos
Multiple Workers in Swift Command Line Tool
Swift 2 iOS 9 Do Catch Try Crashing with Unexpected Nil Found
How to Make the Scroll of a Tableview Inside Scrollview Behave Naturally
How to Check If a Property Value Exists in Array of Objects in Swift
Determine If Any.Type Is Optional
How to Create a View-Based Nstableview Purely in Code
Swift: Orient Y-Axis Toward Another Point in 3-D Space
Compress Image in iOS 12. How Will This Code Be Updated
Linker Command Failed with Exit Code 1 After Installing Cocoapods and Firebase Pod
How to Configure Contextmenu Buttons For Delete and Disabled in Swiftui
Swift: Failing to Copy Files to a Newly Created Folder
How to Get User Home Directory Path (Users/"User Name") Without Knowing the Username in Swift3
Lesser Than or Greater Than in Swift Switch Statement
Why Non Optional Any Can Hold Nil
How to Replicate Promisekit-Style Chained Async Flow Using Combine + Swift
Using Function Parameter Names in Swift
Apply a Shadow on a Uiview That Have Same Corner Radius Than View