@@ -58,21 +58,32 @@ public class SwiftUIContainerView: UIView {
5858 override public func didMoveToWindow( ) {
5959 super. didMoveToWindow ( )
6060
61- if hostingController. parent == nil , let parentViewController = parentViewController {
62- parentViewController. addChild ( hostingController)
63- #if os(iOS) || os(tvOS)
64- hostingController. didMove ( toParent: parentViewController)
65- #endif
61+ if window != nil {
62+ // Add hosting controller to parent view controller hierarchy when view enters window
63+ if hostingController. parent == nil , let parentViewController = parentViewController {
64+ parentViewController. addChild ( hostingController)
65+ #if os(iOS) || os(tvOS)
66+ hostingController. didMove ( toParent: parentViewController)
67+ #endif
68+ }
6669 } else {
67- // hostingController.view.removeFromSuperview()
68- // hostingController.removeFromParent()
70+ // Intentionally NOT removing hosting controller when view leaves window.
71+ // This preserves SwiftUI view state and avoids expensive view tree reconstruction
72+ // when the view temporarily moves out of hierarchy (e.g., during navigation).
73+ // The hosting controller will be properly cleaned up when the container view is deallocated.
6974 }
7075 }
7176
7277 override public func layoutSubviews( ) {
7378 super. layoutSubviews ( )
74- // Ensure the hosting controller's view fills the bounds.
75- hostingController. view. frame = bounds
79+ // Auto Layout constraints handle the hosting controller's view sizing automatically
80+ }
81+
82+ deinit {
83+ // Properly clean up the hosting controller when container view is deallocated
84+ hostingController. willMove ( toParent: nil )
85+ hostingController. view. removeFromSuperview ( )
86+ hostingController. removeFromParent ( )
7687 }
7788}
7889
0 commit comments