Gossamer
Gossamer

Reputation: 309

osx switch between two nsviews

I would like to switch between two NSView controls upon pressing the button. Basically, i have .xib file which contains NSWindow control. Window contains two subviews and few buttons. I have dragged NSViewController in object list and one more NSView in xib. NSViewController has reference to view from NSWindow and view that is floating in xib file.

Question is, how can i switch between nsview1 and nsview2 in NSWindow upon button press? Is this the right way to do it ?

sketch

Upvotes: 2

Views: 1804

Answers (1)

Fruity Geek
Fruity Geek

Reputation: 7381

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];
}

Upvotes: 8

Related Questions