macos 如何打开 NSWindow 并选择窗口并使其处于焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2817714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:56:38  来源:igfitidea点击:

How do I open an NSWindow and have the window selected and in focus?

objective-ccocoamacosnswindownswindowcontroller

提问by Luke

I am trying to open a NSWindow using the following code:

我正在尝试使用以下代码打开一个 NSWindow:

NSWindowController *window = [[NSWindowController alloc] initWithWindowNibName:@"MainWindow"];
[window showWindow:nil];

The window opens okay but the previous window is still the mainWindow and in focus. I have tried the following code to force the main window and it doesn't work. The window still has a disabled title bar and isn't accepting key events etc.

窗口打开正常,但前一个窗口仍然是 mainWindow 并且处于焦点。我尝试了以下代码来强制主窗口,但它不起作用。该窗口仍然有一个禁用的标题栏,并且不接受关键事件等。

[self.window makeKeyAndOrderFront:self];
[self.window makeMainWindow];

The only way I seem to be able to get the previous window to lose focus is if I close the window after calling showWindow: with [[NSApp mainWindow] close];

我似乎能够让前一个窗口失去焦点的唯一方法是,如果我在调用 showWindow: with [[NSApp mainWindow] close]; 后关闭窗口;

Any ideas?

有任何想法吗?

采纳答案by Nikolai Ruhe

makeKeyAndOrderFront:is the way to go. Are you sure that self.windowand windowrefer the same object?

makeKeyAndOrderFront:是要走的路。您确定self.windowwindow引用同一个对象吗?

回答by Luke

I resolved the issue by assigning the WindowController to the nib File Owner, instead of having a separate NSWindowController object within the nib.

我通过将 WindowController 分配给 nib 文件所有者解决了这个问题,而不是在 nib 中有一个单独的 NSWindowController 对象。