Embed a SwiftUI view in an AppKit view

I have a SwiftUI view MySwiftUIView:

import SwiftUI

struct MySwiftUIView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

I want to use it as part of an AppKit view. I tried the following code:

import Cocoa
import SwiftUI

class MyViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview( NSHostingView(rootView: MySwiftUIView()) )
    }
}

with the corresponding storyboard:

storyboard

After the code is built, the result is an empty window:

enter image description here

What I want is this:

enter image description here

How should I make this happen?

Upvotes: 9

Views: 3706

Answers (1)

Asperi
Asperi

Reputation: 257749

You setup subview programmatically, so constraints are on your responsibility, no exception for SwiftUI.

Here is correct variant (tested with Xcode 11.4):

override func viewDidLoad() {
    super.viewDidLoad()

    let myView = NSHostingView(rootView: MySwiftUIView())
    myView.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(myView)
    myView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    myView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}

Upvotes: 12

Related Questions