gpt4 book ai didi

swift - 使用 Swift 创建一个 NSAlert

转载 作者:IT王子 更新时间:2023-10-29 05:01:28 37 4
gpt4 key购买 nike

我有在 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: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.")

根据用户的选择返回truefalse

NSAlertFirstButtonReturn 表示添加到对话框的第一个按钮,这里是“确定”按钮。

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.")

关于swift - 使用 Swift 创建一个 NSAlert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433487/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com