Skip to content

Instantly share code, notes, and snippets.

@Hexfire
Last active April 24, 2017 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hexfire/56c3ef528eab74c2ba00151057a96780 to your computer and use it in GitHub Desktop.
Save Hexfire/56c3ef528eab74c2ba00151057a96780 to your computer and use it in GitHub Desktop.
macOS Modal NSAlert with completion handlers
// As Modal window:
func messageBox(_ title: String!, message: String! = nil,
firstOption: String? = nil, secondOption: String? = nil, thirdOption: String? = nil,
firstAction: (() -> ())? = nil, secondAction: (() -> ())? = nil, thirdAction: (() -> ())? = nil ) {
let alert = NSAlert()
alert.messageText = title ?? ""
alert.informativeText = message ?? ""
[firstOption, secondOption, thirdOption].forEach { if let option = $0 { alert.addButton(withTitle: option) } }
[firstAction ?? {}, secondAction ?? {}, thirdAction ?? {}][alert.runModal() - 1000]?()
}
// As Sheet:
func sheetBox(_ title: String!, message: String? = nil,
firstOption: String? = nil, secondOption: String? = nil, thirdOption: String? = nil,
firstAction: (() -> ())? = nil, secondAction: (() -> ())? = nil, thirdAction: (() -> ())? = nil ) {
let alert = NSAlert()
alert.messageText = title ?? ""
alert.informativeText = message ?? ""
[firstOption, secondOption, thirdOption].forEach { if let option = $0 { alert.addButton(withTitle: option) } }
alert.beginSheetModal(for: NSApp.keyWindow!) {
[firstAction ?? {}, secondAction ?? {}, thirdAction ?? {}][($0 == 0 ? 1000 : $0) - 1000]?()
}
}
// Usage:
messageBox("You are removing recurring event. What should be done?", message: nil,
firstOption: "Remove this event only",
secondOption: "Remove all related events",
thirdOption: "Cancel",
/* UPDATE ONE EVENT */
firstAction:
{
},
/* UPDATE ALL EVENTS */
secondAction:
{
},
/* CANCELLING - DO NOTHING */
thirdAction: nil
)
// Both closures and bottons are optional, hence can be omitted:
messageBox("Hello world")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment