Search code examples
iosswiftxcodescrollcollectionview

Why does Collection View load center carousel with this code?


I've been trying to figure out how to make my collection view of 3 cells load with the 2nd cell, and I finally figured it out after looking through StackOverFlow. However, the code that I came across is a bit confusing to me. Would anyone be able to explain why this code below works in making my collection view cell (that covers the whole screen) start with the 2nd of 3 cells? (this is the effect I wanted to achieve all along, but I want to learn more about why this code works exactly.

In this block of code, there's a bool variable and an if statement, why are they needed? When I took out the boolean variable and if statement, the collection view was unable to scroll.

How does this block of code work exactly?

Thank you.

var onceOnly = false

internal override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if !onceOnly {
        let indexToScrollTo = IndexPath(item: 1, section: 0)
        self.collectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
        onceOnly = true
    }
}

Solution

  • 1- This scrollToItem in Docs

    let indexToScrollTo = IndexPath(item: 1, section: 0)
    self.collectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
    

    makes the collectionView scroll to the second item in the list

    2-

    When I took out the boolean variable and if statement, the collection view was unable to scroll

    Because willDisplay is called for every cell display , so when for example you scroll to 3rd cell willdisplay is called and causes the collectionView to go to the second cell , so it makes it stuck in the second item all the time ( and this seems like no scroll but the scroll happens and you won't notice that as it happens instantly ) , so the boolean var is needed to make that scroll action happens once which is the scroll to the specified index