2

我想NSView在按下按钮时在两个控件之间切换。基本上,我有 .xib 文件,其中包含NSWindow控件。窗口包含两个子视图和几个按钮。我在 xib 中拖NSViewController了一个对象列表和一个。参考了在 xib 文件中浮动的视图和视图。NSViewNSViewControllerNSWindow

问题是,如何在按下按钮时在 nsview1 和 nsview2 之间切换NSWindow?这是正确的方法吗?

草图

4

1 回答 1

8

Define a NSView outlet for the placeholder of where the swappable view is as well as a property for keeping a reference to the current view controller in use.

@property (assign) IBOutlet NSView* mainView;
@property (strong) NSViewController* currentViewController;

I use a generic method for the view swapping (using autolayout to make view take up entire placeholder view).

-(void)setMainViewTo:(NSViewController *)controller
{
    //Remove existing subviews
    while ([[self.mainView subviews] count] > 0)
    {
        [self.mainView.subviews[0] removeFromSuperview];
    }
    NSView * view = [controller view];
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.mainView addSubview:view];

    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(view);   

    [self.mainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:viewsDictionary]];

    [self.mainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:viewsDictionary]];
    self.currentViewController = controller;
}

Now you can define IBOutlets to instantiate and swap your view controllers

-(IBAction)showView1:(id)sender
{
    View1Controller * controller = [[View1Controller alloc]init];
    [self setMainViewTo:controller];
}
-(IBAction)showView2:(id)sender
{
    View2Controller * controller = [[View2Controller alloc]init];
    [self setMainViewTo:controller];
}
于 2013-03-26T21:50:52.577 回答