几乎所有的示例或开源项目均使用xib,现在我需要通过纯代码方式使用NSWindowController
、NSWindow
和NSViewController
三个类搭建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至少存在以下问题:
-
NSWindowController
的loadWindow
、windowDidLoad
、windowWillLoad
方法均不会被调用 - 封装性差
NSWindowController
的loadWindow
、windowDidLoad
、windowWillLoad
方法的官方文档描述如下:
- 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方式。
如若有任何的想法或建议请您不吝笔墨,本人将不胜感激,在此先谢谢各位!
我也想知道怎么实现,同样遇到这个问题。