I needed to get some data from the cell as it was scrolled off of the screen. I used @Mr.T's answer however it doesn't state how to get the data.
Say for example the name of the cell class that I'm using is MyCell
and it has a data model in it named MyModel with a property of postId. I initially set that info in cellForItem
:
var datasource = [MyModel]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCell
cell.myModel = datasource[indexPath.item] // an individual instance of MyModel from the array
print("cellForItem - indexPath.item: ", indexPath.item) // if the was the very first cell coming on it would print 0
print("postId: ", cell.myModel.postId) // maybe the postId is qwerty
return
}
To get some data from the cell as it is scrolled off of the screen:
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let myCell = cell as? MyCell else { return } // You must cast the cell from the method param to your cell type which for me is MyCell
print("didEndDisplayingCell - indexPath.item: ", indexPath.item) // if this was the very first cell scrolling off it should print 0
print("postId: ", myCell.myModel.postId) // the postId should be qwerty
}
The best way to test this is to add a small amount of cells to your collectionView, like first 2 cells, then later on 3 cells, then later on 4 cells. Then just scroll off the very first cell and see what is printed out. Do it for each cell. The indexPath.item and postId should both match for cellForItem
and didEndDisplaying
.