使用 Swift 创建 NSAlert [英] Create an NSAlert with Swift
问题描述
我有在 Objective-C 中创建的代码和 NSAlert,但我现在想在 Swift 中创建它.
I have the code to create and NSAlert in Objective-C but I would now like to create it in Swift.
警报用于确认用户想要删除文档.
The alert is to confirm that the user would like to delete a document.
我想要删除"按钮然后运行删除功能,而取消"按钮只是为了消除警报.
I would like the "delete" button to then run the delete function and the "cancel" one just to dismiss the alert.
我怎样才能用 Swift 写这个?
How can I write this in 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
is deprecated in 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.")
这会根据用户的选择返回 true
或 false
.
This returns true
or false
according to the user's choice.
NSAlertFirstButtonReturn
表示添加到对话框的第一个按钮,这里是OK"按钮.
NSAlertFirstButtonReturn
represents the first button added to the dialog, here the "OK" one.
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
我们现在将枚举用于警报的样式和按钮选择.
We now use enums for the alert's style and the button selection.
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 创建 NSAlert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!