可以通过一种非常简单的技术来实现集合视图中的无限滚动。
注意:据报道,此技术不适用于 iOS 12。为了获得更好的结果,我在解释此方法后添加了一种新方法。
1) 在集合视图的 numberOfItemsInSection 委托方法中返回一个巨大的数字。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return Int(INT_MAX)
}
2) 将集合视图中的项目数与您用来获取重复数据的数组或字典的数量相模。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
cellIdentifier, for: indexPath)
let displayText = indexPath.row % 10
cell.displayLabel.text = String(displayText)
return cell
}
这里我没有数据,因此我使用 indexPath.row 在我的标签中显示行号。
假设我有 10 个数据要显示,并且目前我有大量的项目,所以我对当前项目的编号取模 10。您可以使用数组或字典的计数对行进行取模,如下所示:
let displayText = aryData.count % 10
现在解释另一种适用于任何 iOS 并能提供更好输出的技术:
1)将数组中的项目数乘以2,然后我们需要使用collectionview的内容偏移量。我将在下面发布有关如何处理此技术的代码。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return aryData.count * 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = colView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! colViewCell
var index = indexPath.item
if index > aryData.count - 1 {
index -= aryData.count
}
cell.displayLabel.text = aryData[index % aryData.count]
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// if collection view scrolls vertically, use offset.y else comment below code
var offset = collectionView.contentOffset
let height = collectionView.contentSize.height
if offset.y < height/4 {
offset.y += height/2
collectionView.setContentOffset(offset, animated: false)
} else if offset.y > height/4 * 3 {
offset.y -= height/2
collectionView.setContentOffset(offset, animated: false)
}
// if collection view scrolls horizontally, use offset.x else comment below line of code
// In my case the collectionview scrolls vertically this I am commenting below line of code
// let width = collectionView.contentSize.width
// if offset.x < width/4 {
// offset.x += width/2
// collectionView.setContentOffset(offset, animated: false)
// } else if offset.x > width/4 * 3 {
// offset.x -= width/2
// collectionView.setContentOffset(offset, animated: false)
// }
}
下面是这段代码的输出。
希望对你有帮助:)