collectionView doesn't scrollToItem - swift - programmatically

381 Views Asked by At

I have a UICollectionview set inside a UIView in this way:

videoCollectionView.delegate = self
videoCollectionView.dataSource = self
    
self.playerView.insertSubview(videoCollectionView, belowSubview: additionalItemsView)
videoCollectionView.fillSuperview()

This is how the datasource and delegate methods are implemented

extension CardView : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    let numberOfURLS = cardModel?.urlStrings?.count
    return numberOfURLS!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCellIdentifier", for: indexPath)
    videoCell.backgroundColor = UIColor.random()
    
    return videoCell
    
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.bounds.width, height: self.bounds.height)
}
}

As you can see from the code above each cell is the size of the collectionView.frame I want to have the collectionView cells displayed horizontally and to be able to scroll through them.

this is the code I implemented to scroll horizontally though the cells:

fileprivate func goToNextVideo(){
    
    counter = counter+1
    counter = min(cardModel!.urlStrings!.count-1, counter)
    
    videoCollectionView.scrollToItem(at: IndexPath(item: 0, section: counter), at: .left, animated: true) 
}


fileprivate func goToPreviousVideo(){
    
    counter = counter - 1
    counter = max(0, counter)

    videoCollectionView.scrollToItem(at: IndexPath(item: 0, section: counter), at: .left, animated: true)
}

I don't know for what reason, the collectionView doesn't scroll to the desired cell and I receive this warning in console:

Warning: Invalid IndexPath <NSIndexPath: 0xa5dbc31284d24cfa> {length = 2, path = 1 - 0} specified - will use a contentOffset of {0,0} as a fallback value.
1

There are 1 best solutions below

4
On BEST ANSWER

Looks to me like

IndexPath(item: 0, section: counter)

is backward (twice). Try

IndexPath(item: counter, section: 0)

in both places.