CompositionalList icon indicating copy to clipboard operation
CompositionalList copied to clipboard

Should sync data in `updateUIViewController` method

Open xiaogdgenuine opened this issue 2 years ago • 1 comments

Good library, save me tons of time to adopt CompositionalCollectionViewLayout in SwiftUI by my-self, thank you!

However I notice that the data didn't get sync into Coordinator at all, from my experience, the method makeCoordinator() usually only call once by SwiftUI, after that, even the params passed to the UIViewControllerRepresentable changed, it won't be call again.

Instead, you should sync data manually inside updateUIViewController method, making some adjustments like this in the code can solve the problem:

    public init(_ items: [ViewModel],
                @ViewBuilder cellProvider: @escaping Diff.CellProvider) {
        // This initializer will be invoked every time `items` or `cellProvider` params changed
        self.cellProvider = cellProvider
        self.itemsPerSection = items
    }

    public func makeCoordinator() -> Coordinator {
        // This method usually only call once during UIViewControllerRepresentable's lifecycle, so don't depends on it to sync latest data.
        Coordinator(self)
    }

    public func updateUIViewController(_ uiViewController: Diff, context: Context) {
        // You should add this line to sync latest params into Coordinator instance
        context.coordinator.itemsPerSection = itemsPerSection
        uiViewController.applySnapshotWith(context.coordinator.itemsPerSection)
    }

xiaogdgenuine avatar Nov 13 '23 02:11 xiaogdgenuine

Thanks! would you like to open a PR?

jamesrochabrun avatar Jan 04 '24 05:01 jamesrochabrun