Search code examples
swiftmacosswift3nsapplication

MacOS menu in Swift


I am looking to create a menu sidebar in my application which can display and control view controllers besides the menu. Something like the following: Target User Interface I would like to avoid a TableView for the menu, but I'm not totally against it. I've tried using a TableView and a Container, and a TabViewController but I can't seem to get either to look like the above.

Any help is appreciated, thanks in advance.


Solution

  • Inspiration comes from "What you are looking for is called NSSplitViewController"

    https://stackoverflow.com/questions/30720730/change-views-inside-nssplitviewcontroller

    Code is as follows:

    class MenuController: NSViewController {
        override func loadView() {
            super.loadView()
            tabViewController = parent?.childViewControllers[1] as! NSTabViewController! //The parent is the SplitView, so the child in the second view would be the TabViewController
        }
        @IBOutlet weak var FirstButton: NSButton!
        @IBOutlet weak var SecondButton: NSButton!
    
        var tabViewController = NSTabViewController()
    
        @IBAction func FirstView(_ sender: Any) {
            tabViewController?.selectedTabViewItemIndex = 0 //Now that the TabViewController is specified, one may set the current view controller within the tabview.
        }
    
        @IBAction func SecondView(_ sender: Any) {
            tabViewController?.selectedTabViewItemIndex = 1 //Shows the second view in NSTabViewController
        }
    }
    

    In the diagram, the NSSplitViewController has two childViewControllers; therefore it is the parent of those controllers and can be accessed via the parent? method in both child view controllers. Once you've specified the tabViewController, you can then set its selectedTabViewItemIndex[value] which switches the view in the NSTabViewController.