Search code examples
swiftmacosstoryboardswiftui

How do I link storyboard and swift in a Mac application?


I am trying to IBsegue from the story board to my subclass of NSHostingView. Is this the proper way to link storyboard and SwiftUI for a Mac application?(If not, what is the proper way?) If so, I get four errors in the subclass file:

import Cocoa

class hosty: NSHostingView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }

    @IBSegueAction func termo(_ coder: NSCoder) -> NSViewController? {
        return NSHostingController(coder: coder, rootView: ContentView())
    }
}

Use of undeclared type 'NSHostingView' class hosty: NSHostingView {
Method does not override any method from its superclass override func draw(_ dirtyRect: NSRect) {
'super' members cannot be referenced in a root class super.draw(dirtyRect)
Use of unresolved identifier 'NSHostingController' return NSHostingController(coder: coder, rootView: ContentView())


Solution

  • You need import SwiftUI and specify generics type for NSHostingView like below

    import Cocoa
    import SwiftUI
    
    class hosty: NSHostingView<ContentView> {
    
        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
    
            // Drawing code here.
        }
    
        @IBSegueAction func termo(_ coder: NSCoder) -> NSViewController? {
            return NSHostingController(coder: coder, rootView: ContentView())
        }
    }