【问题标题】:Bring all NSDocument windows to front when opened打开时将所有 NSDocument 窗口置于最前面
【发布时间】:2011-06-10 13:07:01
【问题描述】:

在大多数系统中,“打开一个新窗口”的默认行为是它出现在前面。这在 Cocoa 中不会发生,我正在尝试找到“正确”的方法来实现这种标准行为。我尝试过的大多数事情只适用于最大一个窗口。

我需要在启动时打开多个窗口:

  • (N x NSDocuments(每个窗口一个窗口)
  • 1 x 简单的 NSWindowController,用于打开 NIB 文件。

行不通的事情:

  1. 遍历我要打开的所有 NSDocument,然后打开它们。

会发生什么? ...只有调用 open 的“最后一个”出现在前面 - 其余的都是隐藏的、不可见的,在屏幕上无处可见,直到您快速切换或使用“窗口”菜单找到它们。

代码:

...documents is an array of NSPersistentDocument's, loaded from CoreData...

[NSDocumentController sharedDocumentController];
[controller openDocumentWithContentsOfURL:[documents objectAtIndex:0] display:YES error:&error]; 
  1. 在每个窗口打开后手动调用“makeKeyAndOrderFront”

会发生什么?没什么不同。但是我能找到获取 NSWindow 实例的唯一方法是如此可怕,它似乎完全错误(但在几个博客和邮件列表帖子中都提到了)

代码:

[NSDocumentController sharedDocumentController];
NSDocument* openedDocument = [controller openDocumentWithContentsOfURL:[documents objectAtIndex:0] display:YES error:&error]; 
[[[[openedDocument windowControllers] objectAtIndex:0] window] makeKeyAndOrderFront:nil];

...我知道我做错了,但我不知道为什么/做什么不同:(。

通常但并非总是有效的东西:

  1. 如上所述,但只使用“showWindow”代替(我从 NSDocument 指南中获取)。

奇怪的是,这有时会奏效……尽管这是 Apple 声称他们在内部调用的确切代码。如果他们在内部调用它,如果我在他们已经调用它之后重新调用它,为什么它的行为会有所不同?

[[[openedDocument windowControllers] objectAtIndex:0] showWindow:self];

【问题讨论】:

  • 我也尝试了第三个选项,但是使用 performSelector:withObject:delay: ... 并且它仍然只能随机工作,可能有 50% 的时间,延迟最多 1 秒左右.. . 所以我敢肯定这 - 不知何故 - 从根本上是错误的,否则它会起作用吗?

标签: cocoa nswindow nsdocument nswindowcontroller


【解决方案1】:

您可以直接打开所有文档而不显示,然后告诉文档显示它们的窗口:

NSArray* docs = [NSArray arrayWithObjects:@"doc1.rtf", @"doc2.rtf",@"doc3.rtf",@"doc4.rtf",nil];

for(NSString* doc in docs)
{
    NSURL* url = [NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:doc]];
    NSError* err;
    [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:url display:NO error:&err];
}

[[[NSDocumentController sharedDocumentController] documents] makeObjectsPerformSelector:@selector(showWindows)];

【讨论】:

    【解决方案2】:

    这不行吗?

    对于 10.6 或更高版本

    [[NSRunningApplication currentApplication] activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)];
    

    【讨论】:

      【解决方案3】:

      这通常与应用程序本身有关:您的其他窗口位于其他应用程序的后面(尤其是在 Xcode 后面!),并且会通过隐藏其他命令出现。

      解决该问题的方法是,在将 showWindow 发送到所有窗口(确保最后一个键)之后,您告诉该应用相对于其他应用挺身而出。

      NSApp.activateIgnoringOtherApps(true)  // Swift
      

      [NSApp activateIgnoringOtherApps:YES];  // Objective-C
      

      另请参阅:How to bring NSWindow to front and to the current Space?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-20
        • 2010-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-02
        • 2017-05-17
        相关资源
        最近更新 更多