Skip to content

Commit d117d53

Browse files
Properly add/remove child UIHostingController from parent
1 parent a189db0 commit d117d53

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
@@ -457,24 +457,25 @@ open class ContainerController: NSObject {
457457
// MARK: - Add SwiftUI View
458458

459459
public func removeSwiftUIView() {
460-
// self.hostingController?.willMove(toParent: nil)
460+
self.hostingController?.willMove(toParent: nil)
461461
self.hostingController?.view.removeFromSuperview()
462-
// self.hostingController?.removeFromParent()
462+
self.hostingController?.removeFromParent()
463463
self.hostingController = nil
464464
}
465465

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

480481
// MARK: - Pan Gesture

0 commit comments

Comments
 (0)