更改UICollectionView的反弹起点/终点

时间:2018-11-17 20:39:11

标签: ios swift xcode uicollectionview bounce

通常,当滚动超过它的contentSize时,即当水平方向contentOffset < 0contentOffset > contentSize.width时,UICollectionView开始弹跳

是否可以更改此行为,从而使滚动效果滚动到第10个项目(contentOffset < itemSize.Width * 10contentOffset > contentSize.width - (itemSize.Width * 10)时)开始?

更新1:
@OverD-感谢您为我指明正确的方向。

我在scrollViewWillEndDragging中做了一些工作,并在必要时调整了targetContentOffset

我仍然面临的问题是,弹跳动画不流畅像到达contenSize端时的原始弹跳一样。

任何想法都缺少什么?下面的代码段:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        let numberOfBouncingCells = 10
        let extraSectionWidth = (collectionViewFlowLayout.itemSize.width + collectionViewFlowLayout.minimumLineSpacing) * numberOfBouncingCells

        let startXOffset = extraSectionWidth
        let endXOffset = collectionView.contentSize.width - 2 * extraSectionWidth

        let yOffset = collectionView.contentOffset.y

        if targetContentOffset.pointee.x < startXOffset {
            targetContentOffset.pointee = CGPoint(x: startXOffset, y: yOffset)
        } else if targetContentOffset.pointee.x > endXOffset {
            targetContentOffset.pointee = CGPoint(x: endXOffset, y: yOffset)
        }

    }

更新2(答案):

请参见下面的答案,我放弃了scrollViewWillEndDragging方法,而只想更改collectionView.contentInset [.left, .right]

1 个答案:

答案 0 :(得分:0)

我终于回答了我自己的问题。

我只需要设置collectionView.contentInset [.left, .right]即可达到预期的行为。

var collectionViewFlowLayout: UICollectionViewFlowLayout {
    return collectionView.collectionViewLayout as! UICollectionViewFlowLayout
}

let numberOfBouncingCells = 10
let extraBouncingWidth = (collectionViewFlowLayout.itemSize.width + collectionViewFlowLayout.minimumLineSpacing) * numberOfBouncingCells

collectionView.contentInset.left = -extraBouncingWidth
collectionView.contentInset.right = -extraBouncingWidth