Last active
April 24, 2017 07:58
-
-
Save Hexfire/56c3ef528eab74c2ba00151057a96780 to your computer and use it in GitHub Desktop.
macOS Modal NSAlert with completion handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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