我知道以前有人问过这个问题,但他们都在UITableViews
或UIScrollViews
岁左右,我找不到适合我的被接受的解决方案.我想要的是水平滚动我的UICollectionView
时的捕捉效果-很像iOS AppStore中发生的事情.iOS9+是我的目标版本,所以在回答这个问题之前,请先看看UIKit的变化.
谢谢.
我知道以前有人问过这个问题,但他们都在UITableViews
或UIScrollViews
岁左右,我找不到适合我的被接受的解决方案.我想要的是水平滚动我的UICollectionView
时的捕捉效果-很像iOS AppStore中发生的事情.iOS9+是我的目标版本,所以在回答这个问题之前,请先看看UIKit的变化.
谢谢.
虽然我最初使用的是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
个