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

2021-03-13  本文已影响0人  小白lf
/// 自定义分页
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)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读