9

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?

1 Answers1

10

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
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690