Paging UICollectionView by cells, not screen

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

    Here is the optimised solution in Swift5, including handling the wrong indexPath. - Michael Lin Liu

    • Step1. Get the indexPath of the current cell.
    • Step2. Detect the velocity when scroll.
    • Step3. Increase the indexPath's row when the velocity is increased.
    • Step4. Tell the collection view to scroll to the next item
        func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
            
            targetContentOffset.pointee = scrollView.contentOffset
            
            //M: Get the first visiable item's indexPath from visibaleItems.
            var indexPaths = *YOURCOLLECTIONVIEW*.indexPathsForVisibleItems
            indexPaths.sort()
            var indexPath = indexPaths.first!
    
            //M: Use the velocity to detect the paging control movement.
            //M: If the movement is forward, then increase the indexPath.
            if velocity.x > 0{
                indexPath.row += 1
                
                //M: If the movement is in the next section, which means the indexPath's row is out range. We set the indexPath to the first row of the next section.
                if indexPath.row == *YOURCOLLECTIONVIEW*.numberOfItems(inSection: indexPath.section){
                    indexPath.row = 0
                    indexPath.section += 1
                }
            }
            else{
                //M: If the movement is backward, the indexPath will be automatically changed to the first visiable item which is indexPath.row - 1. So there is no need to write the logic.
            }
            
            //M: Tell the collection view to scroll to the next item.
            *YOURCOLLECTIONVIEW*.scrollToItem(at: indexPath, at: .left, animated: true )
     }
    

提交回复
热议问题