我有在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。
原文链接:https://www.f2er.com/swift/320386.html斯威夫特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.")