水平滚动时,UICollectionView会捕捉到单元格
我知道有些人之前已经问过这个问题,但他们都是关于 UITableViews
或 UIScrollViews
而我无法'获得公认的解决方案,为我工作。我想要的是水平滚动我的 UICollectionView
时的捕捉效果 - 就像在iOS AppStore中发生的那样。 iOS 9+是我的目标版本所以请在回答之前先查看UIKit的更改。
I know some people have asked this question before but they were all about UITableViews
or UIScrollViews
and I couldn't get the accepted solution to work for me. What I would like is the snapping effect when scrolling through my UICollectionView
horizontally - much like what happens in the iOS AppStore. iOS 9+ is my target build so please look at the UIKit changes before answering this.
谢谢。
虽然最初我使用的是Objective-C,但我自从切换到Swift并且原来接受的答案还不够。
While originally I was using Objective-C, I since switched so Swift and the original accepted answer did not suffice.
我结束了创建一个 UICollectionViewLayout
子类,它提供了最好的(imo)体验,而不是在用户停止滚动时改变内容偏移或类似内容的其他函数。
I ended up creating a UICollectionViewLayout
subclass which provides the best (imo) experience as opposed to the other functions which alter content offset or something similar when the user has stopped scrolling.
class SnappingCollectionViewLayout: UICollectionViewFlowLayout {
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) }
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
layoutAttributesArray?.forEach({ (layoutAttributes) in
let itemOffset = layoutAttributes.frame.origin.x
if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset
}
})
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
对于使用当前布局子类的最原始感觉减速,请确保设置以下内容:
For the most native feeling deceleration with the current layout subclass, make sure to set the following:
collectionView?.decelerationRate = UIScrollViewDecelerationRateFast