美文网首页
UICollectionView 自定义分页,实现任意分页效果

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

作者: 小白lf | 来源:发表于2021-03-13 15:25 被阅读0次
/// 自定义分页
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 自定义分页,实现任意分页效果

      本文链接:https://www.haomeiwen.com/subject/tkuxcltx.html