@@ -58,21 +58,32 @@ public class SwiftUIContainerView: UIView {
58
58
override public func didMoveToWindow( ) {
59
59
super. didMoveToWindow ( )
60
60
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
+ }
66
69
} 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.
69
74
}
70
75
}
71
76
72
77
override public func layoutSubviews( ) {
73
78
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 ( )
76
87
}
77
88
}
78
89
0 commit comments