Paging UICollectionView by cells, not screen

前端 未结 22 2147
予麋鹿
予麋鹿 2020-12-04 05:00

I have UICollectionView with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining

22条回答
  •  忘掉有多难
    2020-12-04 05:36

    modify Romulo BM answer for velocity listening

    func scrollViewWillEndDragging(
        _ scrollView: UIScrollView,
        withVelocity velocity: CGPoint,
        targetContentOffset: UnsafeMutablePointer
    ) {
        targetContentOffset.pointee = scrollView.contentOffset
        var indexes = collection.indexPathsForVisibleItems
        indexes.sort()
        var index = indexes.first!
        if velocity.x > 0 {
           index.row += 1
        } else if velocity.x == 0 {
            let cell = self.collection.cellForItem(at: index)!
            let position = self.collection.contentOffset.x - cell.frame.origin.x
            if position > cell.frame.size.width / 2 {
               index.row += 1
            }
        }
    
        self.collection.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
    }
    

提交回复
热议问题