[英]Center the cell of a collectionView everytime the scrollview ends
我有一個collectionView,並且它的scrollview有一個擴展,它可以幫助我在屏幕的右邊獲得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
}
}
我會說
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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.