How to implement horizontally infinite scrolling UICollectionView?

Abdelrahman picture Abdelrahman · Dec 21, 2015 · Viewed 41.3k times · Source

I want to implement UICollectionView that scrolls horizontally and infinitely?

Answer

cicerocamargo picture cicerocamargo · Dec 21, 2015

If your data is static and you want a kind of circular behavior, you can do something like this:

var dataSource = ["item 0", "item 1", "item 2"]

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Int.max // instead of returnin dataSource.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let itemToShow = dataSource[indexPath.row % dataSource.count]
    let cell = UICollectionViewCell() // setup cell with your item and return
    return cell
}

Basically you say to your collection view that you have a huge number of cells (Int.max won't be infinite, but might do the trick), and you access your data source using the % operator. In my example we'll end up with "item 0", "item 1", "item 2", "item 0", "item 1", "item 2" ....

I hope this helps :)