UICollectionView Cell Scroll to centre

后端 未结 6 1281
无人共我
无人共我 2021-02-02 00:28

I am using UICollectionView in my UIViewController.

My collectionview properties are set as below.

\"enter

6条回答
  •  生来不讨喜
    2021-02-02 01:11

    After setting proper itemSize, left and right insets I prefer doing this rather than subclassing layout

    //Setting decelerationRate to fast gives a nice experience
    collectionView.decelerationRate = .fast
    
    //Add this to your view anywhere
    func centerCell () {
        let centerPoint = CGPoint(x: collectionView.contentOffset.x + collectionView.frame.midX, y: 100)
        if let path = collectionView.indexPathForItem(at: centerPoint) {
            collectionView.scrollToItem(at: path, at: .centeredHorizontally, animated: true)
        }
    }
    
    //Set collectionView.delegate = self then add below funcs
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
       centerCell()
    }
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        centerCell()
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            centerCell()
        }
    }
    

提交回复
热议问题