Switching from one NSViewController to another in Swift Storyboards for mac

1.1k Views Asked by At

I have a problem which I am trying to solve for quite a while now. Project file provided also.

So I have the following idea, have a sidebar with buttons, and when the buttons are clicked it switches only the right side content.

I originally created a project that has just 1 storyboard. Window launches the first ViewController, with buttons and a custom view.

What i need is when one of the buttons is pressed that custom view is replaced with contents of another ViewController. Just the view, not the entire previous view controller replaced by another one.

How do i do that? Segues? Layers? Please desperately need help as I cant figure out storyboards but want to work with them a lot. This will get me started.

One other option I was thinking is if I used splitview would it be any better? Then i could probably replace right side view sontroller with another one entirely right?

Link to project file in Xcode

My Storyboard

2

There are 2 best solutions below

0
bob On

I create this with textlable but is the same.

  1. Create "@IBOutlet weak var labelListInvoices : NSTextField!"
  2. Create action "@IBAction func onListInvoices(_ sender: AnyObject) { let act = InvoicesList(nibName: "InvoicesList", bundle: nil) app.show(act!)"
  3. Create a var "var app = NSApp.delegate as! AppDelegate"
  4. Now go to appdelegate and create this func "// APP DIRECTOR

    // Use: // let act = MainView(nibName: "MainView", bundle: nil) // app.show(act!) func show(_ newController: ControllerType, with message: Parameters? = nil) { let newView = newController.view

    if let frame = NSApp.mainWindow?.contentView?.frame {
        newView.frame = frame                           // Resize the view to the window instead
    }
    
    guard let main = NSApp.mainWindow?.contentViewController else { return }
    
    if main.childViewControllers.count < 1 {            // if no controllers, then it's main controller
        main.addChildViewController(newController)                // add new controller
        main.view.addSubview(newView)                   // add new view to main view
        if message != nil {
            newController.notify(message)
        }
    } else {
        let current = main.childViewControllers.last    // get lasr controller as current before adding new
        main.addChildViewController(newController)                // add new controller
        main.transition(from: current!, to: newController, options: [.crossfade]){
            if message != nil {
                newController.notify(message)
            }
        }
    }
    

    } "

0
Арслан Атаев On

You can try to use NSTabView and insert NSTabViewItem objects as much as you need. Each NSTabView can be initiated with custom NSViewController. To hide default tab buttons you can set border type of NSTabView to None. Tabs can be switched programmatically via selectTabViewItem().