Skip to content

Commit 034fd23

Browse files
committed
fix(SwiftUIContainerView): improve hosting controller lifecycle management and preserve SwiftUI view state
fix(SwiftUIRootView): clean up Combine subscriptions in deinit to prevent memory leaks
1 parent 43ac3f5 commit 034fd23

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

ios/SwiftUIContainerView.swift

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -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

ios/SwiftUIRootView.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,4 +258,9 @@ public class SwiftUIRootView: SwiftUIContainerView {
258258
}
259259
return nil
260260
}
261+
262+
deinit {
263+
// Clean up Combine subscriptions to prevent memory leaks
264+
cancellables.removeAll()
265+
}
261266
}

0 commit comments

Comments
 (0)