UICollectionView with Paging Enable

前端 未结 7 1468
天命终不由人
天命终不由人 2021-02-06 09:06

I have to create Grid view like Appstore iOS app. I want to do this with UICollectionView paging. I have also implemented the code but not able to scroll like that.

Wha

7条回答
  •  生来不讨喜
    2021-02-06 09:45

    Ref to Rickster's answer and I rewrite with Swift 4:

    /* paging */
    extension AlbumViewController {
    
        /* In case the user scrolls for a long swipe, the scroll view should animate to the nearest page when the scrollview decelerated. */
        override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            scrollToPage(scrollView, withVelocity: CGPoint(x:0, y:0))
        }
    
        override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
            scrollToPage(scrollView, withVelocity: velocity)
        }
    
        func scrollToPage(_ scrollView: UIScrollView, withVelocity velocity: CGPoint) {
            let cellWidth: CGFloat = cellSize
            let cellPadding: CGFloat = 10
    
            var page: Int = Int((scrollView.contentOffset.x - cellWidth / 2) / (cellWidth + cellPadding) + 1)
            if velocity.x > 0 {
                page += 1
            }
            if velocity.x < 0 {
                page -= 1
            }
            page = max(page, 0)
            let newOffset: CGFloat = CGFloat(page) * (cellWidth + cellPadding)
    
            scrollView.setContentOffset(CGPoint(x:newOffset, y:0), animated: true)
        }
    }
    

提交回复
热议问题