SwiftUI UIHostingController does not update size synchronously, preventing it from being used as a cell within in a UICollectionView

Originator:eric.horacek
Number:rdar://FB9859772 Date Originated:Jan 26, 2022
Status:Open Resolved:
Product:SwiftUI Framework Product Version:iOS 15.2
Classification:Incorrect/Unexpected Behavior Reproducible:Yes
 
In a recent minor version of the iOS 15 SDK (either 15.1 or 15.2), `UIHostingController` now no longer synchronously reflects updates to its `rootView` property, preventing autolayout from sizing cells correctly when a `UIHostingController` is embedded within a cell of a `UICollectionView`. 

There is no public API that forces the the root SwiftUI view to be re-rendered within a `UIHostingController`, and as such when a cell is reused within a `UIHostingController`, the updated content is unable to be measured correctly.

See the attached screen captures, where the bug is not exhibited on iOS 14.5, and is exhibited on iOS 15.2.

We asked about this approach at Apple’s “A conversation with SwiftUI Engineering” on 11/16/21 and Luca Bernardi said that embedding a UIHostingController with a UICollectionViewCell was a reasonable use case to enable gradual adoption of SwiftUI in a UIKit app. However for us to use this approach we need cell reuse and self-sizing cells to function correctly.

Finally, there is a private/underscore-prefixed API that forces a render pass on `UIHostingController`, `_render(seconds:)`, but it is only visible in the SwiftUI `swiftinterface`, so it doesn't seem advisable to rely on it. Calling it whenever the cell is reused does resolve the issue.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!