Skip to content

Commit 099b6e2

Browse files
Properly add/remove child UIHostingController from parent
1 parent 67bfa3c commit 099b6e2

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

Sources/ContainerController/ContainerController.swift

+7-6
Original file line numberDiff line numberDiff line change
@@ -458,24 +458,25 @@ open class ContainerController: NSObject {
458458
// MARK: - Add SwiftUI View
459459

460460
public func removeSwiftUIView() {
461-
// self.hostingController?.willMove(toParent: nil)
461+
self.hostingController?.willMove(toParent: nil)
462462
self.hostingController?.view.removeFromSuperview()
463-
// self.hostingController?.removeFromParent()
463+
self.hostingController?.removeFromParent()
464464
self.hostingController = nil
465465
}
466466

467-
public func add<V: View>(swiftUIView: V) {
467+
public func add<V: View>(swiftUIView: V, parentViewController: UIViewController? = nil) {
468468
guard let contentView = self.view.contentView else {
469469
return
470470
}
471471
removeSwiftUIView()
472472
let hostingController = UIHostingController(rootView: AnyView(swiftUIView))
473473
self.hostingController = hostingController
474-
// self.controller?.addChild(hostingController)
474+
let parent = parentViewController ?? self.controller
475+
parent?.addChild(hostingController)
475476
hostingController.view.frame = contentView.bounds
476-
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
477+
hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
477478
contentView.addSubview(hostingController.view)
478-
// hostingController.didMove(toParent: self.controller)
479+
hostingController.didMove(toParent: parent)
479480
}
480481

481482
// MARK: - Pan Gesture

0 commit comments

Comments
 (0)