Update second view controller in NSSplitViewController
Asked Answered
A

2

5

I have a NSSplitViewController in which first viewcontroller displays a table and second viewcontroller should display a viewcontroller from a list of viewcontrollers based on the selection of table row.

enter image description here

I'm using tableViewSelectionDidChange() to get the selected row.

Now I have a bunch of viewcontrollers(storyboard ID given as row number) that I should add and remove to second viewcontroller in NSSplitViewController

How can I do that?

Axiology answered 20/3, 2017 at 4:55 Comment(0)
A
11

You are on the right path. Within tableViewSelectionDidChange() you need to instantiate a new viewController from your storyboard using NSStoryboards instantiateController(withIdentifier: String) method. Then you can set this as your splitViews second view controller.

Then you need to create a splitViewItem. You can use the init method which takes a viewController for this (NSSplitViewItem(viewController:)).

Finally you have two possibilities to add the new viewController. Either you use the add/removeSplitViewItem methods or you set the splitViewItems array directly.

My words in code:

guard let splitViewController = self.parent as? NSSplitViewController,
      let viewController = self.storyboard?.instantiateController(withIdentifier: "yourIdentifier") as? NSViewController
        else { return }

let item = NSSplitViewItem(viewController: viewController)

// Method one
splitViewController.removeSplitViewItem(splitViewController.splitViewItems[1])
splitViewController.addSplitViewItem(item)

// OR method two
var items = splitViewController.splitViewItems
items[1] = item
splitViewController.splitViewItems = items
Armyworm answered 20/3, 2017 at 6:7 Comment(3)
It works! But there's a small mistake in the method two. Change parent to splitViewController.Axiology
This is great, thanks! One question: why not just add the new VC like so: splitViewController.splitViewItems[1] = item?Acree
I'm not sure if it's an AppKit bug but if I assign the same item twice using splitViewController.splitViewItems[1] = item (eg if the user clicks the same table row twice) the split view disappears. Using "Method one" resolves this issue.Acree
U
0

Objective C representation of the first method.

NSStoryboard * mainStoryboard = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
NSViewController * sourceViewController = [mainStoryboard instantiateControllerWithIdentifier:identrifier];

NSSplitViewItem * item = [NSSplitViewItem splitViewItemWithViewController:sourceViewController];

[self removeSplitViewItem:[self.splitViewItems objectAtIndex:1]];
[self addSplitViewItem:item];
Unparalleled answered 25/7, 2019 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.