SwiftUI with UICollectionView
Article Summary
Kari Grooms from Expedia Group tackles a problem every iOS team faces: how do you start using SwiftUI when your app is built on UICollectionView? Her solution is clever, but comes with some surprising gotchas.
With iOS 13 still in play and UICollectionView powering critical features like search results and discovery feeds, many teams can't wait for LazyVStack. Grooms walks through embedding SwiftUI views inside UICollectionViewCell, complete with proper UIHostingController setup, data passing patterns, and real-world layout challenges from the Vrbo iOS app.
Key Takeaways
- UIHostingController must be added as child controller to avoid memory leaks
- Never use @State in embedded SwiftUI views; cells get reused and state disappears
- SwiftUI buttons break UICollectionView's didSelectItemAt delegate method
- Use @EnvironmentObject to preserve state across cell reuse cycles
- fitToAspectRatio modifier prevents image skewing in fixed-size cells
You can embed SwiftUI in UICollectionViewCell, but interactive elements require workarounds and the approach only makes sense for specific use cases.
About This Article
Kari Grooms at Expedia Group was integrating SwiftUI views into UICollectionViewCell. The challenge was keeping the view controller hierarchy intact to avoid memory leaks and views disappearing unexpectedly.
Grooms created helper methods to add and remove UIHostingController as a child view controller. Instead of initializing everything during cell setup, she moved that logic into an embed() method that updates rootView when the cell gets reused.
This approach stopped unintended side effects from happening. SwiftUI Card views now render consistently across Vrbo's discovery feeds, search results, and trip boards without creating duplicate UIHostingControllers.