UICollectionView with Paging Enable

前端 未结 7 1480
天命终不由人
天命终不由人 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:31

    full source is here

    this supports RTL (Right to Left)

    collectionView.decelerationRate = .fast
    
    
    // paging
    extension ViewController: UIScrollViewDelegate {
        
        func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
            self.dragStartPoint = scrollView.contentOffset
        }
        
        func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
            let isRTL = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
            let pageWidth = UIScreen.main.bounds.size.width - ViewController.left - ViewController.right + ViewController.lineSpacing
            
            if scrollView.contentOffset.x == targetContentOffset.pointee.x { // no decelerate
                if fabsf(Float(self.dragStartPoint.x - scrollView.contentOffset.x)) > 40 { // min move distance = 40
                    let dragLeft = self.dragStartPoint.x < scrollView.contentOffset.x
                    if dragLeft {
                        self.currentPage = isRTL ? self.currentPage - 1 : self.currentPage + 1
                    } else {
                        self.currentPage = isRTL ? self.currentPage + 1 : self.currentPage - 1
                    }
                }
            } else if scrollView.contentOffset.x > targetContentOffset.pointee.x {
                let maxRight = scrollView.contentSize.width - UIScreen.main.bounds.size.width
                if scrollView.contentOffset.x <= maxRight { // not right bounce
                    self.currentPage = isRTL ? self.currentPage + 1 : self.currentPage - 1
                }
            } else {
                if scrollView.contentOffset.x >= 0 { // not left bounce
                    self.currentPage = isRTL ? self.currentPage - 1 : self.currentPage + 1
                }
            }
            
            self.currentPage = max(0, self.currentPage)
            self.currentPage = min(self.numberOfPages - 1, self.currentPage)
            
            var offset = targetContentOffset.pointee
            if isRTL {
                offset.x = CGFloat(self.numberOfPages - self.currentPage - 1) * pageWidth
            } else {
                offset.x = CGFloat(self.currentPage) * pageWidth
            }
            targetContentOffset.pointee = offset
        }
    }
    
    
    

提交回复
热议问题