Oliver Koehler
Oliver Koehler

Reputation: 721

NSTabViewController add NSToolbarItems

I'd like to use the NSTabViewController for switching through 6 different Tabs with the toolbar style.

All tabs have in common that they show different aspects of a Customer entity.

Now I want to add aditional NSToolbarItems to the toolbar of the NSTabViewController? But I haven't found a way to access the toolbar. I also would like to add Space between the ToolbarItems.

Is there a way to do so?

Or how can I add my ViewController from the Storyboard to a NSTabView without using NSTabViewController?

Regards

Oliver


In the meantime I've tried another approach that I thought was more promising but lead to another strange behaviour:

I've created a new NSViewController and put a NSTabView inside. In order to load my already existing ViewControllers I used this

override func viewDidLoad() {
    super.viewDidLoad()
    let customerController = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("CustomerVCID")) as! CustomerViewController

    let servicesController = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("ServicesVCID")) as! ServicesController

    customerController.customer = self.customer
    servicesController.customer = self.customer

    self.tabView.tabViewItems[0].view = customerController.view
    self.tabView.tabViewItems[1].view = servicesController.view

}

That indeed worked, but now all my NSButtons that have actions will cause my application to crash.

Upvotes: 0

Views: 867

Answers (1)

Marek H
Marek H

Reputation: 5566

There is only one toolbar per window. So your NSTabViewController shares it.

  1. Select toolbar mode of NSTabViewController
  2. Override NSWindowController and add your items

Example:

  override func windowDidLoad() {
      super.windowDidLoad()
      window?.toolbar?.insertItem(withItemIdentifier: .print, at: 0)
  }

You can always access your toolbar via following path view->window->toolbar

Your only issue is that there is one delegate per NSToolbar. Which means you have to create your custom NSToolbarItem inside NSTabViewController delegate.

   override func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
        if itemIdentifier == .export {
            return ExportToolbarItem.new()
        } else {
            return super.toolbar(toolbar, itemForItemIdentifier: itemIdentifier, willBeInsertedIntoToolbar: flag)
        }
    }

Remember your are required to call super. This is because underlying method wants to create bindings to view controller. In case you need actionable buttons in toolbar just add them without calling super.

Upvotes: 1

Related Questions