I need to embed a SwiftUI View
into a UIViewController
's view.
Do I need to write addChild(hostingController)
and hostingController.didMove(toParent: self)
at the end of viewDidLoad()
?
class EmbedSwiftUIViewViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swiftUIView = SwiftUIView()
let hostingController = UIHostingController(rootView: swiftUIView)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
])
// Do I need to write this two lines?
// addChild(hostingController)
// hostingController.didMove(toParent: self)
}
}
struct SwiftUIView: View {
var body: some View {
ZStack {
Color.blue
Text("SwiftUI View")
}
}
}
If I write it, the swipe gesture to back is disabled, but if I don't write it, the swipe gesture works fine.
This may be a problem specific to my project environment, but I would like to know if there is any problem without writing addChild()
and didMove(toParent:)
anyway.