(OSX/Cocoa) 如何设置主控制器 window

(OSX/Cocoa) How to set controller for main window

我已经使用 .xib 文件创建了一个新的 cocoa 应用程序(不是故事板,该应用程序必须向后兼容 mavericks/mountain lion)并且我想要一个自定义的 window 主控制器 window。这可能吗?我似乎找不到将 window 连接到我想要的自定义控制器的方法。 window 在 AppDelegate 中有一个参考插座,但是我需要为此 window 定制一个 NSWindowController,因为它不会在应用程序启动时打开。该应用程序作为菜单栏应用程序静默启动,主应用程序通过按下菜单栏下拉菜单中的按钮启动。

有没有办法在界面生成器中 link 控制器到 window?还是我必须按照以下方式做一些事情:

 wc = [[CustomWindowController alloc] initWithWindowNibName:@"Main"];

谢谢!

创建控制器并使其从 NSWindowController 扩展。 在您的 xib 文件中 select 文件所有者并将其设置为您的自定义 class。 Select 您的 NSWindow 并将其连接到文件所有者。

打开window:

在你的.h中:

@property (strong, nonatomic) YourWindowController *yourWinController;

在你的.m中:

self.yourWinController = [[YourWindowController alloc] initWithWindowNibName:@"YourWindowController"];
[self.yourWinController showWindow: nil];

是的,在 Interface Builder 中打开 Utilities(右侧面板),然后单击底部的 Object Library(带正方形的圆圈)。
搜索 Object(蓝色立方体),并将其拖到您的 Document Outline(界面生成器左侧面板)
从那里,select 您刚刚创建的对象,并将 Identity Inspector 中的 Class 更改为您想要的 window 控制器。

最后你可以进入 Connections Inspector 并将你的 window 连接到 window 插座

I can't seem to find a way to connect the window to my desired custom controller. The window has a reference outlet in AppDelegate, however I need a custom NSWindowController for this window as it doesn't open on application launch.

另一种方式:

1) 删除MainMenu.xib中的window。删除AppDelegate.m中的window属性--因为你删除了window,它不再相关。

2) 文件>新建>文件>Cocoa Class。输入 class 名称,例如主窗口控制器; select "Subclass of: NSWindowController";检查 "Also create .xib file for user interface".

3) 在 AppDelegate.m 中创建出口:

#import "AppDelegate.h"
#import "MainWindowController.h"

@interface AppDelegate ()

@property (strong, nonatomic) MainWindowController* windowController;

@end

4) 在AppDelegate.h中声明一个动作:

@interface AppDelegate : NSObject <NSApplicationDelegate>

-(IBAction)launchWindow:(id)sender;

@end

并在AppDelegate.m中实施:

- (void)launchWindow:(id)sender {
    [self setWindowController:[[MainWindowController alloc]
                               initWithWindowNibName:@"MainWindowController"]];

    [[self windowController] showWindow:nil];
}

5) 在 MainMenu.xib 中,将菜单项连接到 launchWindow() 操作:控制从菜单项拖动到 AppDelegate 对象和 select launchWindow。