使用 Swift 创建 NSAlert

2017-05-09  本文已影响541人  张嘉夫

我们都知道如何用 Objective-C 创建 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];

假设 alert 用于确认用户是否想删除某个文档。

我们希望“删除”按钮运行删除函数,“取消”按钮只需隐藏 alert 即可。

但如何用 Swift 实现呢?

从 OS X 10.10 Yosemite 版本开始 beginSheetModalForWindow:modalDelegate 就已经被弃用了

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: "确认?", text: "请选择。")

该方法根据用的选择返回 truefalse

NSAlertFirstButtonReturn 表示添加进 alert 的第一个按钮,这里就是“好的”。

上一篇下一篇

猜你喜欢

热点阅读