我們都知道如何用 Objective-C 創(chuàng)建 NSAlert:
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:@"Delete"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Delete the document?"];
[alert setInformativeText:@"Are you sure you would like to delete the document?"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
假設(shè) alert 用于確認(rèn)用戶是否想刪除某個(gè)文檔。
我們希望“刪除”按鈕運(yùn)行刪除函數(shù),“取消”按鈕只需隱藏 alert 即可。
但如何用 Swift 實(shí)現(xiàn)呢?
從 OS X 10.10 Yosemite 版本開始 beginSheetModalForWindow:modalDelegate 就已經(jīng)被棄用了
func dialogOKCancel(question: String, text: String) -> Bool {
let myPopup: NSAlert = NSAlert()
myPopup.messageText = question
myPopup.informativeText = text
myPopup.alertStyle = NSAlertStyle.warning
myPopup.addButton(withTitle: "好的")
myPopup.addButton(withTitle: "取消")
return myPopup.runModal() == NSAlertFirstButtonReturn
}
let answer = dialogOKCancel(question: "確認(rèn)?", text: "請(qǐng)選擇。")
該方法根據(jù)用的選擇返回 true 或 false。
NSAlertFirstButtonReturn 表示添加進(jìn) alert 的第一個(gè)按鈕,這里就是“好的”。