Home > database >  Enable only forward swiping in UICollectionView
Enable only forward swiping in UICollectionView

Time:10-27

I have a UICollectionView in which I am displaying a UICollectionViewCell. Each cell has the same height and width as the collection view.

I want to restrict the user to swipe back to the UICollectionViewCell after they have proceeded to the next cell

Something like a tinder experience, Although I have Pagination enabled in my UICollectionView

CodePudding user response:

You can do this with following steps

You have to get the current row after scroll end and update the current index in your

currentIndex

object Then allow view to scroll or not. Make sure you have calculated the cell width proper with left right edges also and cell space of collection view

var currentIndex = 0
var cellWidth = 0.0


func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            let row = scrollView.contentOffset.x / cellWidth
            currentIndex = Int(row)
        }

func scrollViewDidScroll(_ scrollView: UIScrollView) {

        if scrollView.contentOffset.x < cellWidth * CGFloat(currentIndex){
            scrollView.contentOffset =  CGPoint(x: cellWidth * CGFloat(currentIndex), y: -20)
            scrollView.bounces = false
        } else {
            scrollView.bounces = true
        }
    }

CodePudding user response:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    
    let indexPathOfVisible = collectionView.indexPath(for: collectionView.visibleCells.first ?? UICollectionViewCell())
    
    if indexPath.row < indexPathOfVisible?.row ?? 0 {
        collectionView.scrollToItem(at: indexPathOfVisible!, at: .right, animated: false)
    } 
}
  • Related