我有在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中已弃用。
beginSheetModalForWindow:modalDelegate
迅捷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.")
返回true或false根据用户的选择。
true
false
NSAlertFirstButtonReturn 表示添加到对话框的第一个按钮,此处为“确定”。
NSAlertFirstButtonReturn
迅捷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.")
斯威夫特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.")