gpt4 book ai didi

ios - 水平滚动 UICollectionView 时对齐单元格的中心

转载 作者:IT老高 更新时间:2023-10-28 11:36:35 26 4
gpt4 key购买 nike

我知道有些人以前问过这个问题,但他们都是关于 UITableViewsUIScrollViews 的,我无法得到可接受的解决方案来为我工作。我想要的是水平滚动我的 UICollectionView 时的捕捉效果——就像在 iOS AppStore 中发生的一样。 iOS 9+ 是我的目标版本,所以在回答这个问题之前请先查看 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

关于ios - 水平滚动 UICollectionView 时对齐单元格的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com