Paging UICollectionView by cells, not screen

前端 未结 22 2118
予麋鹿
予麋鹿 2020-12-04 05:00

I have UICollectionView with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining

22条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 05:54

    final class PagingFlowLayout: UICollectionViewFlowLayout {
        private var currentIndex = 0
    
        override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
            let count = collectionView!.numberOfItems(inSection: 0)
            let currentAttribute = layoutAttributesForItem(
                at: IndexPath(item: currentIndex, section: 0)
                ) ?? UICollectionViewLayoutAttributes()
    
            let direction = proposedContentOffset.x > currentAttribute.frame.minX
            if collectionView!.contentOffset.x + collectionView!.bounds.width < collectionView!.contentSize.width || currentIndex < count - 1 {
                currentIndex += direction ? 1 : -1
                currentIndex = max(min(currentIndex, count - 1), 0)
            }
    
            let indexPath = IndexPath(item: currentIndex, section: 0)
            let closestAttribute = layoutAttributesForItem(at: indexPath) ?? UICollectionViewLayoutAttributes()
    
            let centerOffset = collectionView!.bounds.size.width / 2
            return CGPoint(x: closestAttribute.center.x - centerOffset, y: 0)
        }
    }
    

提交回复
热议问题