在 Cocoa 的非故事板应用程序上登陆 "ViewController"

Landing on a "ViewController" on a non-storyboard app on Cocoa

我是 cocoa 开发新手。

当我在 Xcode 上使用情节提要创建一个新项目时,它使用 iOS 模型,我更喜欢这种模型,它有一个 viewController 和一个委托,它们是单独的文件.然后我使用 viewController 开始我的项目并向其视图添加内容。

当我创建一个不使用故事板的新项目时,启动项目的 "landing page" 是 window,我首先向其添加视图。

我不喜欢这个模型的地方是我必须将代码添加到委托文件中。我不喜欢那样。我喜欢 AppDelegate.h 和 .m 仅包含核心数据和基本代码来启动应用程序并将命令传递给另一个 class.

我根本不会再在 cocoa 上使用故事板,因为它们在 Cocoa 上是一大堆 bug 和半生不熟的实现。 NSSavePanel/NSOpenPanel 不起作用,SplitViewControllers 和 Tabs 效果不佳。可惜了。

如何在 cocoa 上的非故事板应用程序上执行此操作?我的意思是,是否可以将控制权传递给 viewController 或将另一个 class 与应用程序委托分开作为应用程序的起点?

像这样的东西应该可以工作:

在 main.m 中执行以下操作:

int main(int argc, const char * argv[]) {
    AppDelegate * delegate = [[AppDelegate alloc] init];
    [[NSApplication sharedApplication] setDelegate:delegate];
    [NSApp run];
}

在AppDelegate.m以下:

@interface AppDelegate ()
@property (nonatomic,strong) NSWindow *window;
@property (nonatomic,strong) MainViewController *masterViewController;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.masterViewController = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    self.window  = [[NSWindow alloc] initWithContentRect:NSMakeRect(200, 200, 200, 200)
                                                     styleMask:NSResizableWindowMask
                                                       backing:NSBackingStoreBuffered
                                                         defer:NO];
    [self.window.contentView addSubview:self.masterViewController.view];
    self.masterViewController.view.frame = ((NSView*)self.window.contentView).bounds;
    [self.window makeKeyAndOrderFront:NSApp];
}

这将为您提供由 MainViewController 控制的可调整大小的视图。您将需要创建 class 并使用或不使用 XIB 对其进行配置。您可以从作为主界面的目标设置和项目中删除 MainMenu.xib。