加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

用Swift创建NSAlert

发布时间:2020-12-14 05:51:57 所属栏目:百科 来源:网络整理
导读:我有在Objective-C中创建和NSAlert的代码,但我现在想在Swift中创建它。 警报是确认用户想要删除文档。 我想要“删除”按钮,然后运行删除功能和“取消”只是为了关闭警报。 我如何在Swift写这个? 谢谢 NSAlert *alert = [[[NSAlert alloc] init] autorelea
我有在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.")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读