Home > Software design >  How to reload collectionview while still keeping order when adding new data
How to reload collectionview while still keeping order when adding new data

Time:12-09

I implemented Pagination into my project and noticed when inserting new data and reloading the collectionview I would go from Item 52 to Item 34. Is there anyway to stay at Item 52 and going on instead of going back to Item 34? Any help would be appreciated

Gif of problem

CodePudding user response:

you can try the following solution with different way

  1. you can reload the collection for last visible index

    yourCollectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)

  2. call the below method when add new item || on cell selection || from any other method from where you want to update the collection items get the index path which you want to view and pass into method

     func reloadCollectionView(collectionView: UICollectionView,index:IndexPath){
    
     let contentOffset = collectionView.contentOffset
     collectionView.reloadData()
     collectionView.layoutIfNeeded()
     collectionView.setContentOffset(contentOffset, animated: false)
     collectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: false) 
     }
    

e.g in collection did select item i'm calling this method with following way

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      self.reloadCollectionView(collectionView: self.yourCollectionView, index: indexPath)

}

Hope this solution may helps you

  • Related