我有一个collectionView,我的滚动视图有一个扩展名,可以帮助我在屏幕右侧获取我的单元格20像素(下一个单元格的最小空间),如下所示:
我的扩展是这样的:(如果我可以用任何其他方式随意告诉它)
extension MyProject : UIScrollViewDelegate
{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
答案 0 :(得分:3)
我说
offset = CGPoint(
x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left + cellWithIncludingSpacing / 2 - scrollView.bounds.size.width / 2,
y: -scrollView.contentInset.top
)
或者,更好地考虑contentInset
let visibleWidth = scrollView.bounds.size.width
- scrollView.contentInset.left
- scrollView.contentInset.right
offset = CGPoint(
x: roundedIndex * cellWidthIncludingSpacing
- scrollView.contentInset.left
+ layout.itemSize.width / 2
- visibleWidth / 2,
y: -scrollView.contentInset.top
)