Detect visible cell inside CollectionView and call function

Hi,


I'm trying to get the current visible cell from my collectionview and call a function based upon the indexPath row value.

I tried to use willDisplayCell but when I added an if else conditional it fired when the cells weren't visible. I also tried

indexPathsForVisibleItems but this too failed to work.


The functionality should be when the cell index is 0 run one method else run another.


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     
        if collectionView == self.locationsCollectionView {
         
            let cell = locationsCollectionView.dequeueReusableCell(withReuseIdentifier: "storedLocationCell", for: indexPath) as! StoredLocationsCell
         

            let storedLocation = storedLocationsData[indexPath.row]
         
            
            cell.locationCity.text = storedLocation.name?.uppercased()
            cell.locationRegion.text = storedLocation.region?.uppercased()
            for label in cell.labelSpacing {
                label.addTextSpacing(1)
            }
            cell.locationRegion.textColor = lightGreyColor
         
            return cell
         
        }
}


Thanks!

Answered by JayCo in 208881022

I managed to find the solution, turns out another method was calling reloadData, creating an infinite loop. Hope it helps anyone.

I've managed to find some sort of way but the getAnotherLocation() is firing multiple times inside willDisplayCell.


func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if collectionView == self.locationsCollectionView {
            let storedLocation = storedLocationsData[indexPath.row]
           
            if indexPath.row != 0 {
                print(storedLocation.name!)
                getAnotherLocation(lat: storedLocation.latitude, lon: storedLocation.longitude, spinner: true)
            }
            if indexPath.row == 0 {
                print(storedLocation.name!)
            }
           
        } else {
           
        }
    }


I don't understand why it's firing multiple times. Is there a refresh method that keeps calling on willDisplay Cell?

Accepted Answer

I managed to find the solution, turns out another method was calling reloadData, creating an infinite loop. Hope it helps anyone.

Detect visible cell inside CollectionView and call function
 
 
Q