NSViewController and multiple subviews from a Nib

删除回忆录丶 提交于 2019-11-28 03:02:36

When breaking out each view into its own nib and using NSViewController, the typical way of handling things is to create an NSViewController subclass for each of your nibs. The File's Owner for each respective nib file would then be set to that NSViewController subclass, and you would hook up the view outlet to your custom view in the nib. Then, in the view controller that controls the main window content view, you instantiate an instance of each NSViewController subclass, then add that controller's view to your window.

A quick bit of code - in this code, I'm calling the main content view controller MainViewController, the controller for the "toolbar" is TopViewController, and the rest of the content is ContentViewController

//MainViewController.h
@interface MainViewController : NSViewController
{
    //These would just be custom views included in the main nib file that serve
    //as placeholders for where to insert the views coming from other nibs
    IBOutlet NSView* topView;
    IBOutlet NSView* contentView;
    TopViewController* topViewController;
    ContentViewController* contentViewController;
}

@end

//MainViewController.m
@implementation MainViewController

//loadView is declared in NSViewController, but awakeFromNib would work also
//this is preferred to doing things in initWithNibName:bundle: because
//views are loaded lazily, so you don't need to go loading the other nibs
//until your own nib has actually been loaded.
- (void)loadView
{
    [super loadView];
    topViewController = [[TopViewController alloc] initWithNibName:@"TopView" bundle:nil];
    [[topViewController view] setFrame:[topView frame]];
    [[self view] replaceSubview:topView with:[topViewController view]];
    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentView" bundle:nil];
    [[contentViewController view] setFrame:[contentView frame]];
    [[self view] replaceSubview:contentView with:[contentViewController view]];
}

@end

Should not MainViewController be a subclass of NSWindowController? And the outlets in the class connected to view elements in the main Window in MainMenu.xib? Let's hope old threads are still read...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!