(Swift, macOS, Storyboards)
How to open a View with code and macOS? (a View, not a Window)
I can open a Window Controller:
var controller: NSWindowController?
if controller == nil {
let storyboard:NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
controller = storyboard.instantiateController(withIdentifier: "window1") as? NSWindowController
}
controller?.showWindow(self)
But I could not figure out how to open a View Controller. What would the be equivalent code for a View Controller in macOS?
Your set up is more clear with the screen shot.
So I went to test it in code.
- I created a new class, as SecondViewController
import Cocoa
class SecondViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
- I created a second view, in IB (as you did), as SecondViewController, with storyboard ID
SecondView
- I created a button "Load Second View" in first view.
Its action is
@IBAction func loadSecondView(_ sender: NSButton) {
let storyboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let myViewController = storyboard.instantiateController(withIdentifier: "SecondView") as? SecondViewController
self.view.window?.contentViewController = myViewController
}
When I click in Load Second View, second view shows.
NOTE: when you answer don't just say: it gives me error. Tell exactly what the error is.