![](/img/trans.png)
[英]CollectionView Cell changing size after scrolling - AutoLayout
[英]CollectionView Cell gets shifted to right after horizontal Scrolling
原因是在設置單元格寬度時沒有采用minimum separation of 10
(320)。 因此,每次滾動都會累積這個10
。
因此,在設置寬度時,您必須減去320中的10個,因此寬度應為310 IMO。
我假設您已為集合視圖設置了pagingEnabled
。 它從UIScrollView
繼承此屬性(因為UICollectionView
是UIScrollView
的子類)。
問題是集合視圖使用自己的寬度(帖子中的320個點)作為頁面的寬度。 您的每個單元格與集合視圖的寬度相同,但是在單元格之間有10個“溝槽”。 這意味着從單元格0的左邊緣到單元格1的左邊緣的距離是320 + 10 = 330點。 因此,當您滾動顯示單元格1時,集合視圖將停止在偏移320(其自身寬度)處滾動,但單元格1實際上從偏移330處開始。
最簡單的修復可能是通過在集合視圖委托中覆蓋scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)
來關閉pagingEnabled
並自己實現分頁,如下所示:
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return }
let pageWidth = scrollView.bounds.size.width + flowLayout.minimumInteritemSpacing
let currentPageNumber = round(scrollView.contentOffset.x / pageWidth)
let maxPageNumber = CGFloat(collectionView?.numberOfItems(inSection: 0) ?? 0)
// Don't turn more than one more page when decelerating, and don't go beyond the first or last page.
var pageNumber = round(targetContentOffset.pointee.x / pageWidth)
pageNumber = max(0, currentPageNumber - 1, pageNumber)
pageNumber = min(maxPageNumber, currentPageNumber + 1, pageNumber)
targetContentOffset.pointee.x = pageNumber * pageWidth
}
您還需要設置項目大小以匹配設備屏幕大小,並將減速率設置為快速:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let collectionView = collectionView else { return }
flowLayout.itemSize = collectionView.bounds.size
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.