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 Answer 1

12

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 } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.