我知道有些人以前问过这个问题,但他们都是关于UITableViews
or UIScrollViews
我无法得到适合我的可接受的解决方案。我想要的是滚动浏览时的捕捉效果UICollectionView
水平 - 很像 iOS AppStore 中发生的情况。 iOS 9+ 是我的目标版本,因此请在回答此问题之前查看 UIKit 更改。
Thanks.
虽然最初我使用的是 Objective-C,但后来我改用了 Swift,最初接受的答案还不够。
我最终创建了一个UICollectionViewLayout
子类提供了最好的(imo)体验,而不是其他在用户停止滚动时改变内容偏移或类似内容的函数。
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)
}
}
为了使用当前布局子类获得最原生的减速感觉,请确保设置以下内容:
collectionView?.decelerationRate = UIScrollViewDecelerationRateFast
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)