简体   繁体   English

在MacOS中以编程方式关闭模式对话框

[英]Programmatically dismiss modal dialog in MacOS

I have a warning dialog from a MacOS application's AppDelegate that needs to be updated with new information. 我有一个来自MacOS应用程序的AppDelegate的警告对话框,需要使用新信息进行更新。 When the new information is available, I want to programmatically dismiss the old dialog and present the new one. 当有新信息可用时,我想以编程方式关闭旧对话框并显示新对话框。 I have tried this two ways, both with problems: 我尝试了两种方式,但都存在问题:

  1. Using alert.runModal() 使用alert.runModal()

    If I use the above, a modal is presented as desired. 如果我使用上面的方法,则会根据需要呈现一个模态。 I can then dismiss the dialog later with lockWarningModal.window.close() , it works to make the old dialog disappear, but it freezes the UI, so I can no longer interact with it. 然后,我可以稍后使用lockWarningModal.window.close()关闭该对话框,它可以使旧对话框消失, 但是它冻结了UI,因此我无法再与之交互。 I am guessing this is because alert.runModal() is synchronous, and the main thread is still blocked. 我猜这是因为alert.runModal()是同步的,并且主线程仍然被阻塞。 However, I don't know how to release this. 但是,我不知道该如何发布。

  2. Using alert.beginSheetModal(for: NSApplication.shared.windows.last!) { (response) in } 使用alert.beginSheetModal(for: NSApplication.shared.windows.last!) { (response) in }

    If I use the above and dismiss the dialog with NSApplication.shared.windows.last!.endSheet(alert.window) , then this solves the UI freeze problem. 如果我使用上述方法并使用NSApplication.shared.windows.last!.endSheet(alert.window)关闭对话框,则可以解决UI冻结问题。 However, the dialog is attached to the main application window and is not brought to the front as a modal. 但是, 该对话框已附加到主应用程序窗口 ,而未作为模态显示在最前面。

How can I achieve a modal dialog that is programmatically dismissible? 如何获得以编程方式可忽略的模式对话框?

You can't stop a model event loop (or alert sheet) by simply closing its window. 您不能通过简单地关闭其事件窗口来停止模型事件循环(或警报表)。 In fact, using the modern NSAlert API, you should never have to close or order out the window—the framework handles this for you. 实际上,使用现代的NSAlert API,您永远不必关闭或订购该窗口-框架会为您处理。

For an alert started with runModal() use NSApplication 's abortModal() , stopModal() , or stopModal(withCode:) . 对于以runModal()开头的警报,请使用NSApplicationabortModal()stopModal()stopModal(withCode:) After runModal() returns, send the alert window an orderOut(nil) to remove it. runModal()返回之后,向警报窗口发送orderOut(nil)将其删除。

For an alert sheet that executes a completion block afterwards, use NSWindow 's endSheet(_) or endSheet(_:returnCode:) . 对于随后执行完成块的警报表,请使用NSWindowendSheet(_)endSheet(_:returnCode:) The alert will be automatically removed after your completion block executes. 您的完成区块执行后,警报将自动删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM