NSViewController和Nib的多个子视图

jbr*_*nan 25 cocoa interface-builder nib nsviewcontroller

我很难用Interface Builder和NSViewController来加载视图.

我的目标是拥有一个符合以下描述的视图:顶部的顶部栏(如工具栏但不完全)跨越整个视图宽度,下面是第二个"内容视图".该复合视图由我的NSViewController子类拥有.

为此使用Interface Builder是有意义的.我创建了一个视图笔尖,并在其中添加了两个子视图,将它们正确放置(使用顶部栏和内容视图).我已经准备File's OwnerMyViewController,并连接插座等.

我希望加载的视图(条形图和内容)也在它们自己的笔尖中(这可能是让我沮丧的),并且这些笔尖将其自定义类设置为适用的相应NSView子类.我不确定要设置什么File's Owner(我猜MyController它应该是他们的主人).

唉,当我初始化一个MyViewController实际上没有我的笔尖的实例时.我已经正确地将它添加到我的Window的contentView(我已经检查过了),实际上,有些东西是加载的.也就是说,awakeFromNib会被发送到条形图,但它不会显示在窗口中.我想我肯定有一些电线穿过某处.也许有人可以帮助减轻我的一些挫败感?

编辑一些代码来显示我正在做的事情

当应用程序完成启动时,从应用程序委托中加载控制器:

MyController *controller = [[MyController alloc] initWithNibName:@"MyController" bundle:nil];
[window setContentView:[controller view]];
Run Code Online (Sandbox Code Playgroud)

然后在我的initWithNibName中,我现在不做任何事情,而是打电话给super.

Bri*_*ter 71

将每个视图分解为自己的nib并使用时NSViewController,处理事物的典型方法是NSViewController为每个nib 创建一个子类.然后,每个相应nib文件的文件所有者将被设置为该NSViewController子类,并且您可以将view插座连接到笔尖中的自定义视图.然后,在控制主窗口内容视图的视图控制器中,实例化每个NSViewController子类的实例,然后将该控制器的视图添加到窗口中.

快速的代码 - 在这段代码中,我正在调用主内容视图控制器MainViewController,"工具栏"的控制器是TopViewController,其余的内容是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
Run Code Online (Sandbox Code Playgroud)