我在Objective中有要创建的代码和NSAlert,但是现在我想用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];发布于 2015-04-03 14:00:59
beginSheetModalForWindow:modalDelegate在OSX10.10Yosemite中是不可取的。
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。
NSAlertFirstButtonReturn表示添加到对话框中的第一个按钮,这里是"OK“按钮。
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.")发布于 2016-04-30 12:26:18
我想这可能对你有用..。
let a = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButtonWithTitle("Delete")
a.addButtonWithTitle("Cancel")
a.alertStyle = NSAlert.Style.WarningAlertStyle
a.beginSheetModalForWindow(self.view.window!, completionHandler: { (modalResponse) -> Void in
if modalResponse == NSAlertFirstButtonReturn {
print("Document deleted")
}
})发布于 2018-06-30 13:11:35
更新Jose Hidalgo对Swift 4的回答:
let a: NSAlert = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButton(withTitle: "Delete")
a.addButton(withTitle: "Cancel")
a.alertStyle = NSAlert.Style.warning
a.beginSheetModal(for: self.window!, completionHandler: { (modalResponse: NSApplication.ModalResponse) -> Void in
if(modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn){
print("Document deleted")
}
})https://stackoverflow.com/questions/29433487
复制相似问题