0

I'm working with a UICollectionView as UIViewRepresentable. It should be updated when either current item is changed (to scroll to the current item and highlight it), or the source data was updated (it can add/remove one item). The first case works perfectly, but the second one can cause lags and even crash the app with this exception: "Attempted to scroll the collection view to an out-of-bounds item (9) when there are only 9 items in section 0". It's caused when scrolling after updating the source data (adding/removing item).

Here is the code for updateUIView function:

func updateUIView(_ uiView: UICollectionView, context: Context) {
        uiView.reloadData()

        if !sections.isEmpty, currentSectionId != context.coordinator.currentSectionIndex && uiView.numberOfItems(inSection: 0) == sections.count {
            context.coordinator.currentSectionIndex = currentSectionId
            
            guard let currentSection = sections.firstIndex(where: { $0.id == currentSectionId }) else { return }
            let indexPath = IndexPath(row: currentSection, section: 0)

            uiView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        }
    }

And here are the variables of my UIViewRepresentable:

struct SectionScrollView: UIViewRepresentable {
    @Binding var sections: [MenuSection]
    @Binding var currentSectionId: Int

It's a menu that can be navigated through categories so scrolling main menu (also UIViewRepresentable UICollectionView) triggers currentSectionId that scrolls section collection view to the current section. And pressing current section in section collection view triggers main collection view to scroll to the beginning current section.

Also, making an item favorite adds additional section (if there is no favorites) and removes it (if user removes the last item from favorites). And here is when the exception appear. If the user scrolls main collection view after making item favorite, the app could crash (or could not).

It seems that reloadData() doesn't always work or work as expected.

So, what could be wrong here?

P.S. When I add the code below to updateUIView, the scrolling sometimes stops until another favorite dish isn't added/removed:

uiView.reloadData() // This was already there

if sections.count != uiView.numberOfItems(inSection: 0) {
    uiView.reloadData()
}
  • how do you add the value for ```numberOfItemsInSection``` in ```UICollectionViewDataSource```? – udi Feb 11 '22 at 12:20
  • @udi in context.coordinator that is my UICollectionViews' dataSource I write in this function: `return parent.section.count` – alexantonov Feb 11 '22 at 12:26

0 Answers0