FSPagerView icon indicating copy to clipboard operation
FSPagerView copied to clipboard

scrollToItem forces crash in case of index out of range

Open adomanski opened this issue 4 years ago • 6 comments

The method scrollToItem validates the index and forces crash if the index is out of range of already built items. This looks correct but one notice: when we call scrollToItem we cannot be sure that index is correct because we have no way to verify its value. So could you please:

  1. add logic to bypass crash (or create new method which don't produce crash or add new parameter, etc.)
  2. or make accessible numberOfItems value

Thanks a lot for your awesome library

adomanski avatar Sep 19 '19 04:09 adomanski

I had the same problem, and I could try this if I only had one section pagerView.scrollToItem(at: index, animated: true)

ls19491314 avatar Sep 21 '19 07:09 ls19491314

I am having the same issue myself. I am trying to reload the pager view data and then scroll to an item after a delay like this:

        self.pagerView.reloadData()

        DispatchQueue.main.async {
            // A trick how we can wait for the collection view to finish the reload

            if parentCard.currentItemIndex < ((parentCard.data as? DailyPlanFeedGalleryDisplayable)?.imageItems.count ?? 0) {
                self.pagerView.scrollToItem(at: parentCard.currentItemIndex, animated: false)
            }
        }

This works most of the time, but sometimes for some reason this fails and the pagerView crashes. We either need a way to verify the index ourselves or this needs to fail safely.

r00li avatar Oct 23 '19 08:10 r00li

Just do this:

self.pagerView.layoutIfNeeded()
self.pagerView.reloadData()
self.pagerView.scrollToItem(at: index, animated: true)

dingronghui avatar Mar 25 '20 08:03 dingronghui

+1 on this, a lot of folks are getting this crash (numerous other issues) we at a minimum need read access to numberOfItems so we can make this fail safely.

Update: After doing some more digging I found that UICollectionView#reloadData will update numberOfItems immediately if you call layoutIfNeeded afterwards. You should also make sure to call reloadData and scrollToItem on the main thread. Unfortunately, it's not a great fix for all cases considering the potential performance impact.

benatautolist avatar Oct 27 '20 22:10 benatautolist

forcing a fatalError on scrollToItem is a very bad idea, please remove that line. If the app scroll to a out-of-index item, just scroll to the maximum index (or do nothing if empty item) instead.

kennic avatar Oct 30 '20 05:10 kennic

let numberOfItems = self.dataSource?.numberOfItems(in: self) ?? 0

superno02 avatar Mar 09 '22 10:03 superno02