beginSheetModalForWindow:modalDelegate
在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.")
根据用户的选择,这将返回true
或false
。
NSAlertFirstButtonReturn
代表对话框中添加的第一个按钮,这里是“OK”按钮。
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
现在我们使用枚举来表示警告框的样式和按钮的选择。
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.")
beginSheetModal(for:completionHandler:)
并没有被弃用,事实上这可能是处理模态对话框(在块中)更理想的方式。它也更接近具有didEndSelector
的旧方式,并且不会停止整个应用程序。 - Patru