Reputation: 2448
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:
After the code is built, the result is an empty window:
What I want is this:
How should I make this happen?
Upvotes: 9
Views: 3706
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