swiftstoryboardswiftuisubclassnsviewcontroller

What is the correct subclass to link storyboard and swiftUI?


I have created the subclass below to link my swiftui code to my storyboard. The goal is to have a vstack with text containers in it display inside a ContainerView. I am not sure if I am using the right class: NSViewController? I do not get any errors, but the code does not display how I want it to. Mostly, The swiftui does not display inside the window that shows up when I run the app.

import SwiftUI

class termu: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
    }
    @IBSegueAction func waka(_ coder: NSCoder) -> NSViewController? {
        return NSHostingController(coder: coder, rootView: ContentView())
    }

}

Solution

  • Here is the simplest MyViewController which you can specify for new controller scene in IB for your storyboard as custom class in Identity Inspector. (The controller scene and segue creation in IB as usual).

    view controller

    I selected Sheet segue for demo

    SwiftUI segue controller

    import Cocoa
    import SwiftUI
    
    class MyViewController: NSHostingController<ContentView> {
    
        @objc required dynamic init?(coder: NSCoder) {
            super.init(coder: coder, rootView: ContentView())
        }
    }
    
    struct ContentView: View { // This SwiftUI view is just for Demo
        var body: some View {
            VStack {
                Text("I'm SwiftUI")
                    .font(.largeTitle)
                    .padding()
                    .background(Color.yellow)
            }
            .frame(width: 400, height: 200)
        }
    }