Reputation: 41
I want to make an infinite scroll collection view, so in this code I add 10 to the number of cells every time the index path is equals to the last cell item, and then reload the data in the collection. The function works; I can scroll infinitely, but if I stop, and then scroll a little up or down, everything is blank. The cells aren't showing.
My theory is that it has something to do with dequeueReusableCellWithReuseIdentifier, and it decides to only show the cells that are currently on the screen.
View when scrolling (I added the numbers to the cells outside of Xcode)
View with the missing cells above when scrolling a bit after stopping
private let reuseIdentifier = "Cell"
private var numberOfCells = 20
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
if indexPath.row == numberOfCells - 1 {
numberOfCells += 10
self.collectionView?.reloadData()
}
cell.contentView.backgroundColor = UIColor.blueColor()
return cell
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfCells
}
}
Upvotes: 2
Views: 1550
Reputation: 322
Swift 4.2
reload it like this.
DispatchQueue.main.async(execute: collectionView.reloadData)
Upvotes: 0
Reputation: 520
var numberOfCells: Int = 20 {
didSet {
if numberOfCells != oldValue {
self.collectionView?.reloadData()
}
}
}
Upvotes: 1
Reputation: 139
I am doing similar things in Table View and it is working for me. The only difference is that if indexPath.row
is last cell then I am calling another function which do some stuff (required for me) and calling reloadData()
into that function only. Try this way, I am not sure, but it may solve your problem.
Upvotes: 0
Reputation: 4198
Calling reloadData
from cellForItemAtIndexPath
is bad. Use other delegate method for that, for example, scrollViewDidScroll
.
Upvotes: 2