【问题标题】:Check if NSAlert is currently showing up检查 NSAlert 当前是否出现
【发布时间】:2016-07-09 12:24:16
【问题描述】:

我正在使用NSAlert 在我的应用程序的主屏幕上显示错误消息。 基本上,NSAlert 是我的主视图控制器的属性

class ViewController: NSViewController {

    var alert: NSAlert?

    ...

}

当我收到一些通知时,我会显示一些消息

func operationDidFail(notification: NSNotification)
{
    dispatch_async(dispatch_get_main_queue(), {

        self.alert = NSAlert()
        self.alert.messageText = "Operation failed"
        alert.runModal();
    })
}

现在,如果我收到多个通知,则每个通知都会显示警报。我的意思是,它出现在第一条消息中,我点击“确定”,它消失了,然后再次出现在第二条消息中等等......这是正常行为。

我想要实现的是避免这一系列错误消息。其实我只关心第一个。 有没有办法知道我的警报视图当前是否正在显示? 类似于 iOS 的 UIAlertView 上的 alert.isVisible

【问题讨论】:

    标签: swift macos cocoa nsalert


    【解决方案1】:

    从您的代码中,我怀疑通知是在后台线程中触发的。在这种情况下,任何检查警报现在是否可见都无济于事。在第一个块完成之前,您的代码不会开始后续块执行,因为runModal 方法将阻塞,在模态模式下运行NSRunLoop

    为了解决您的问题,您可以引入 atomic bool 属性并在dispatch_async 之前检查它。

    Objective-C 解决方案:

    - (void)operationDidFail:(NSNotification *)note {
        if (!self.alertDispatched) {
            self.alertDispatched = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.alert = [NSAlert new];
                self.alert.messageText = @"Operation failed";
                [self.alert runModal];
                self.alertDispatched = NO;
            });
        }
    }
    

    使用 Swift 的相同代码:

    func operationDidFail(notification: NSNotification)
    {
        if !self.alertDispatched {
            self.alertDispatched = true
            dispatch_async(dispatch_get_main_queue(), {
                self.alert = NSAlert()
                self.alert.messageText = "Operation failed"
                self.alert.runModal();
                self.alertDispatched = false
            })
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试运行模式而不是运行模式

      - beginSheetModalForWindow:completionHandler:
      

      来源:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAlert_Class/#//apple_ref/occ/instm/NSAlert/beginSheetModalForWindow:completionHandler

      在完成处理程序中,将 alert 属性设置为 nil。 并且仅在警报属性为 nil 时才显示警报(这将是在解除警报后的每一次)。 编辑:我没有看到文档说明您要查找的任何类型的标志。

      【讨论】:

      • 谢谢,这也可以。不过我接受了鲍里斯的回答,因为我想继续使用runModal
      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2022-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多