Paging UICollectionView by cells, not screen

前端 未结 22 2066
予麋鹿
予麋鹿 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:37

    The original answer of Олень Безрогий had an issue, so on the last cell collection view was scrolling to the beginning

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
        targetContentOffset.pointee = scrollView.contentOffset
        var indexes = yourCollectionView.indexPathsForVisibleItems
        indexes.sort()
        var index = indexes.first!
        // if velocity.x > 0 && (Get the number of items from your data) > index.row + 1 {
        if velocity.x > 0 && yourCollectionView.numberOfItems(inSection: 0) > index.row + 1 {
           index.row += 1
        } else if velocity.x == 0 {
            let cell = yourCollectionView.cellForItem(at: index)!
            let position = yourCollectionView.contentOffset.x - cell.frame.origin.x
            if position > cell.frame.size.width / 2 {
               index.row += 1
            }
        }
        
        yourCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
    }
    

提交回复
热议问题