用Swift创建NSAlert

我有在Objective-C中创建和NSAlert的代码,但我现在想在Swift中创建它。

警报是确认用户想要删除文档。

我想要“删除”按钮,然后运行删除功能和“取消”只是为了关闭警报。

我如何在Swift写这个?

谢谢

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];
beginSheetModalForWindow:在OS X 10.10 Yosemite中不推荐使用modalDelegate。

斯威夫特2

func dialogoKCancel(question: String,text: String) -> Bool {
    let myPopup: NSAlert = NSAlert()
    myPopup.messageText = question
    myPopup.informativeText = text
    myPopup.alertStyle = NSAlertStyle.WarningalertStyle
    myPopup.addButtonWithTitle("OK")
    myPopup.addButtonWithTitle("Cancel")
    let res = myPopup.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 myPopup: NSAlert = NSAlert()
    myPopup.messageText = question
    myPopup.informativeText = text
    myPopup.alertStyle = NSAlertStyle.warning
    myPopup.addButton(withTitle: "OK")
    myPopup.addButton(withTitle: "Cancel")
    return myPopup.runModal() == NSAlertFirstButtonReturn
}

let answer = dialogoKCancel(question: "Ok?",text: "Choose your answer.")

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...