(OSX/Cocoa) 如何为主窗口设置控制器

3
我创建了一个新的cocoa应用程序,使用.xib文件(而不是storyboard),该应用程序必须向下兼容mavericks/mountain lion。我想为主窗口创建一个自定义windowcontroller,这是否可行?我无法找到连接窗口到所需自定义控制器的方法。窗口在AppDelegate中有一个引用outlet,但是我需要为此窗口定制一个NSWindowController,因为它不会在应用程序启动时打开。该应用程序静默启动为菜单栏应用程序,并通过菜单栏中的按钮按下来启动主应用程序。

是否有一种方法可以在界面生成器中将控制器链接到窗口?还是我必须做类似这样的事情:

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

谢谢!

3个回答

3
我似乎找不到将窗口连接到所需的自定义控制器的方法。该窗口在AppDelegate中具有引用出口,但是我需要一个自定义NSWindowController来处理此窗口,因为它不会在应用程序启动时打开。
另一种方法:
1)删除MainMenu.xib中的窗口。删除AppDelegate.m中的窗口属性——因为您删除了窗口,所以它已不再相关。
2)文件>新建>文件>Cocoa Class。输入类名,例如MainWindowController;选择“子类:NSWindowController”;勾选“还为用户界面创建.xib文件”。
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对象拖动并选择launchWindow。


这不会将窗口设置为mainWindow - Andy Hin

3
是的,在Interface Builder中打开“Utilities”(右侧面板),然后在底部点击“Object Library”(圆形内含正方形)。 搜索“Object”(蓝色立方体),并将其拖到您的“Document Outline”(界面构建器内部的左侧面板)中。 从那里,选择您刚创建的对象,并在“Identity Inspector”中更改“Class”为您想要的窗口控制器。 最后,您可以进入“Connections Inspector”并将您的“window”连接到“window”输出口。

这个方法可以运行,但是无法按照以下方式实例化窗口: mainAppController = [[Testcontroller alloc] initWithWindowNibName:@"MainMenu"]; [mainAppController showWindow:self]; 我收到了以下错误信息:无法连接(Testcontroller)的(delegate)输出到(AppDelegate):缺少setter或实例变量。 - Julian Hunt
mainAppController是一个局部变量吗?根据你的片段,看起来是这样的。尝试创建一个属性(实例变量),如下所示:@property Testcontroller *mainAppController。然后使用self.mainAppController引用它。同时将nil作为参数传递给-showWindow方法。最后,请确保您的File's Owner(应用程序委托)不再连接到窗口。单击File's Owner,转到连接检查器,并确保删除该连接。 - A O

0
创建控制器并使其扩展自NSWindowController。 在xib文件中选择“File's Owner”并将其设置为您的自定义类。 选择您的NSWindow并将其连接到“File's Owner”。
打开窗口: 在您的.h文件中:
@property (strong, nonatomic) YourWindowController *yourWinController;

在你的 .m 文件中:

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

我不确定这对我的情况是否有效,因为我正在谈论使用空应用程序创建的“MainMenu.xib”。当前文件所有者的类型为NSApplication。将其设置为NSWindowController会不会引起问题?你上面提到的是我在只包含窗口的.xib文件中所做的事情。然而,MainMenu.xib还包含其他对象。 - Julian Hunt
为什么不为你的窗口创建一个单独的xib呢? - albertoqa
我可以这样做,但是我将不得不复制所有的东西,比如出现在菜单栏左上角的菜单等。我只需要一种简单的方法来从AppDelegate之外的某个按钮点击启动这个主窗口。 - Julian Hunt
我认为你无法在NSApplication(MainMenu.xib的文件所有者)和nib之间获取NSWindowController。 - albertoqa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接