UICollectionView Cell Scroll to centre

后端 未结 6 1283
无人共我
无人共我 2021-02-02 00:28

I am using UICollectionView in my UIViewController.

My collectionview properties are set as below.

\"enter

6条回答
  •  青春惊慌失措
    2021-02-02 01:24

    Here's a Swift 3 version of @dmitry-zhukov (thanks btw!)

    class PagedCollectionLayout : UICollectionViewFlowLayout {
    
        var previousOffset : CGFloat = 0
        var currentPage : CGFloat = 0
    
        override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
    
            let sup = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
    
            guard
                let validCollection = collectionView,
                let dataSource = validCollection.dataSource
                else { return sup }
    
            let itemsCount = dataSource.collectionView(validCollection, numberOfItemsInSection: 0)
    
            // Imitating paging behaviour
            // Check previous offset and scroll direction
            if  (previousOffset > validCollection.contentOffset.x) && (velocity.x < 0) {
                currentPage = max(currentPage - 1, 0)
            }
            else if (previousOffset < validCollection.contentOffset.x) && (velocity.x > 0) {
                currentPage = min(currentPage + 1, CGFloat(itemsCount - 1))
            }
    
            // Update offset by using item size + spacing
            let updatedOffset = ((itemSize.width + minimumInteritemSpacing) * currentPage)
            self.previousOffset = updatedOffset
    
            let updatedPoint = CGPoint(x: updatedOffset, y: proposedContentOffset.y)
    
            return updatedPoint
        }
    }
    

提交回复
热议问题