怎样使用纯代码方式搭建macOS App UI界面?

ShawnTing
  • 5
新手上路,请多包涵

几乎所有的示例或开源项目均使用xib,现在我需要通过纯代码方式使用NSWindowController NSWindowNSViewController 三个类搭建UI界面。

通过如下代码能够成功的显示界面,但我个人感觉这似乎不是正确的创建方式。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application

MainViewController *mainVC = [[MainViewController alloc] init];
mainVC.title = @"CocoaDemo";

MainWindow *mainWindow = [MainWindow windowWithContentViewController:mainVC];
[mainWindow makeKeyAndOrderFront:nil];
[mainWindow center];

// Create a window controller
MainWindowController *mainWC = [[MainWindowController alloc] initWithWindow:mainWindow];
// Put the window of the window controller on screen
[mainWC showWindow:self];
self.mainWC = mainWC;
}

而且通过上述方式创建UI至少存在以下问题:

  1. NSWindowControllerloadWindowwindowDidLoadwindowWillLoad方法均不会被调用
  2. 封装性差

NSWindowControllerloadWindowwindowDidLoadwindowWillLoad方法的官方文档描述如下:

- loadWindow Loads the receiver’s window from the nib file.
You should never directly invoke this method. Instead, access the window property so the windowDidLoad and windowWillLoad methods are invoked. Subclasses can override this method if the way it finds and loads the window is not adequate. It uses the NSBundle class’s bundleForClass: method to get the bundle, using the class of the nib file owner as argument. It then locates the nib file within the bundle and, if successful, loads it; if unsuccessful, it tries to find the nib file in the main bundle.

- windowDidLoad Sent after the window owned by the receiver has been loaded.
The default implementation does nothing.

- windowWillLoad Sent before the window owned by the receiver is loaded.
The default implementation does nothing.

根据字面理解这三个方法作用也不太明确,请各位大神传授正确地纯代码创建macOS App方式。

如若有任何的想法或建议请您不吝笔墨,本人将不胜感激,在此先谢谢各位!

回复
阅读 3.3k
1 个回答

我也想知道怎么实现,同样遇到这个问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏