2

I'm working on a CollectionView with many cells in it. And what I am trying to do is:

  • When the user is on the last cell of collectionView, and when the user swipes to see the next cell, I want this collectionView to restarts from the beginning. ( Basically, I need an endless loop )

Hope I could explain it correctly. Waiting for your solutions. Thank you.

Mr. T.
  • 93
  • 11

1 Answers1

-1

Try this.

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate=self;
        collectionView.dataSource=self;
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100;
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
        cell.backgroundColor = UIColor.red
        if indexpath.row==99{
            self.btnScroll()
           }
        return cell
    }

    func btnScroll() {
        collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: UICollectionView.ScrollPosition.top, animated:true)
    }
}
Sagar koyani
  • 403
  • 2
  • 12
  • 1
    unfortunately, this is scrolling to first item, what I need is showing the first item after the last one and continue to scroll like I have more contents in that collectionView – Mr. T. Jan 04 '19 at 08:48
  • This is really bad advice, `cellForItemAt` is likely to be also called when prefetching cells, or scrolling back, I doubt in those cases you'll want to automatically scroll to the first item. – Cristik Aug 23 '22 at 04:35