Paging UICollectionView by cells, not screen

前端 未结 22 2058
予麋鹿
予麋鹿 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:45

    Here is my version of it in Swift 3. Calculate the offset after scrolling ended and adjust the offset with animation.

    collectionLayout is a UICollectionViewFlowLayout()

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = scrollView.contentOffset.x / collectionLayout.itemSize.width
        let fracPart = index.truncatingRemainder(dividingBy: 1)
        let item= Int(fracPart >= 0.5 ? ceil(index) : floor(index))
    
        let indexPath = IndexPath(item: item, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
    

提交回复
热议问题