UICollectionView Cell Scroll to centre

后端 未结 6 1228
无人共我
无人共我 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:25

    I have found a lot of information and solutions.

    now, I use this.

    on UICollectionViewFlowLayout override:

    override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
    
        if display != .inline {
            return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
        }
    
        guard let collectionView = collectionView else {
            return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
        }
    
        let willtoNextX: CGFloat
    
        if proposedContentOffset.x <= 0 || collectionView.contentOffset == proposedContentOffset {
            willtoNextX = proposedContentOffset.x
        } else {
    
            let width = collectionView.bounds.size.width
            willtoNextX = collectionView.contentOffset.x + (velocity.x > 0 ?  width : -width)
        }
    
        let targetRect = CGRect(x: willtoNextX, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
    
        var offsetAdjustCoefficient = CGFloat.greatestFiniteMagnitude
    
        let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left
    
        let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
    
        layoutAttributesArray?.forEach({ (layoutAttributes) in
            let itemOffset = layoutAttributes.frame.origin.x
            if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustCoefficient)) {
                offsetAdjustCoefficient = itemOffset - horizontalOffset
            }
        })
    
        return CGPoint(x: proposedContentOffset.x + offsetAdjustCoefficient, y: proposedContentOffset.y)
    }
    

    and on UICollectionViewController:

    collectionView.decelerationRate = .fast
    collectionView.isPagingEnabled = false
    collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)
    

    now, cell is in center!!

    preview

提交回复
热议问题