UICollectionView 自定义分页,实现任意分页效果

/// 自定义分页
public class ShtPageCollectionViewLayout: UICollectionViewFlowLayout {
    override public func prepare() {
        super.prepare()
        collectionView?.decelerationRate = .fast
        collectionView?.isPagingEnabled = false
    }
    
    override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = collectionView else {
            return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
        }
        
        let pageWidth = itemSize.width + minimumLineSpacing
        
        let approximatePage = collectionView.contentOffset.x / pageWidth
        
        let currentPage = velocity.x == 0 ? round(approximatePage) : (velocity.x < 0.0 ? floor(approximatePage) : ceil(approximatePage))
        
        let margin = (collectionView.bounds.size.width - itemSize.width) * 0.5
        
        let newHorizontalOffset = sectionInset.left + currentPage * pageWidth - margin

        return CGPoint(x: newHorizontalOffset, y: proposedContentOffset.y)
    }
}

你可能感兴趣的:(UICollectionView 自定义分页,实现任意分页效果)