Home > Net >  MacOS app unable to instantiate SwiftUI view as a root view controller
MacOS app unable to instantiate SwiftUI view as a root view controller

Time:10-03

I am trying to load SwiftUI view as a first view controller for macOS app, unfortunately it doesn't show anything in macOS window. Below is how I wrote the app delegate for macOS.

class AppDelegate: NSObject, NSApplicationDelegate {

    let contentView = NSHostingController(rootView: ContentView.init())


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        let storyBoard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: Bundle.main)
        let window = storyBoard.instantiateController(withIdentifier: "Main Window") as! NSWindowController

        window.contentViewController = contentView
    }
}

ContentView

struct ContentView: View {
    var body: some View {
        Text.init("Hello World!")
    }
}

This is the output enter image description here

My goal is I want to set rootViewController for macOS and this view controller is made in SwiftUI. Any help is highly appreciated.

CodePudding user response:

I assume you just see window of initial window controller created from storyboard automatically and don't see your programmatically created window because of content view zero size.

So a) make sure initial window controller is deactivated

demo1

and b) add size of content view (you need this because you do everything programmatically), like

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World!")
        }
        .frame(width: 800, height: 600)    // << here !!
    }
}

Update: store created window controller into local property

class AppDelegate: NSObject, NSApplicationDelegate {

    
    let contentView = NSHostingController(rootView: ContentView())
    private var window: NSWindowController! // << here !!

    ...

        window.contentViewController = contentView
        window.showWindow(nil)

Tested with Xcode 13 / macOS 11.6 (on test project created from scratch)

  • Related