【问题标题】:Can NSAlert Be Used to Create a Floating Window?NSAlert 可以用来创建浮动窗口吗?
【发布时间】:2010-10-20 09:47:09
【问题描述】:

我有一个 Cocoa 应用程序,它使用 NSAlert 类显示应用程序模式警报。我希望警报窗口浮动在所有其他应用程序的窗口之上。这可以用NSAlert 完成,还是我需要实现自己的窗口?

我不知道这些是否重要,但该应用程序是一个代理应用程序(LSUIElement 是真的)实现为NSStatusItem。 (有关该应用程序的更多信息,包括源代码,请查看<here>。)

这是显示警报的代码:

- (void)showTimerExpiredAlert {
    [NSApp activateIgnoringOtherApps:YES];

    NSAlert *alert = [[NSAlert alloc] init];
    [alert setAlertStyle:NSInformationalAlertStyle];
    [alert setMessageText:NSLocalizedString(@"Menubar Countdown Complete", @"Expiration message")];
    [alert setInformativeText:NSLocalizedString(@"The countdown timer has reached 00:00:00.",
                                                @"Expiration information")];
    [alert addButtonWithTitle:NSLocalizedString(@"OK", @"OK button title")];
    [alert addButtonWithTitle:NSLocalizedString(@"Restart Countdown...", @"Restart button title")];

    NSInteger clickedButton = [alert runModal];
    [alert release];

    if (clickedButton == NSAlertSecondButtonReturn) {
        // ...
    }
}

我试过把这个放在runModal 调用之前:

[[alert window] setFloatingPanel:YES];

我也试过这个:

[[alert window] setLevel:NSFloatingWindowLevel];

但是如果我单击另一个应用程序的窗口,这些都不会使窗口停留在其他窗口之上。我怀疑runModal 只是不尊重这些设置。

【问题讨论】:

  • 每当调用 runModal 时,它都会重置窗口级别,不确定是否有帮助...

标签: cocoa nsalert


【解决方案1】:

我最终放弃了NSAlert,而是从NIB 加载了一个警报NSWindow

这是显示窗口的代码:

- (void)showAlert {
    NSWindow *w = [self window];
    [w makeFirstResponder:nil];
    [w setLevel:NSFloatingWindowLevel];
    [w center];
    [w makeKeyAndOrderFront:self];
}

这是为了让它像一个警报一样,除了它也浮动,它不是模态的,所以菜单项可以在它启动时选择。

还有什么我应该做的吗?

【讨论】:

    【解决方案2】:

    前段时间,我为这件事伤透了脑筋。

    我可以让它工作(有点)的唯一方法是继承 NSApplication,并覆盖 -sendEvent。在 -sendEvent 中,首先调用 super 的实现,然后执行如下操作:

    id *modalWindow = [self modalWindow];
    if (modalWindow && [modalWindow level] != MY_DESIRED_MODAL_WINDOW_LEVEL)
        [modalWindow setLevel: MY_DESIRED_MODAL_WINDOW_LEVEL];
    

    除此之外,即使这样也不能一尘不染——在切换应用程序时——你无论如何都不想这样做,因为这是一种公然粗暴的黑客行为。

    所以是的,遗憾的是,您最好编写自己的 NSAlert 版本。如果你真的关心这种可能性,我会在上面提交一个错误。很奇怪 [[alert window] setLevel: someLevel] 不被 NSApplication 认可,并且为了能够做到这一点而不得不重新构建 NSAlert 及其所有简洁的自动布局功能是一种浪费。

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 2013-01-27
      • 1970-01-01
      相关资源
      最近更新 更多