Search code examples
swifttableviewcell

Cells Disappear when Scrolling a TableView (Swift)


I am fairly new to Swift and am a bit confused. I have programmed my Firestore to load data into a TableView. However, when I scroll through the load data within the tableView, the cells within the tableView disappear. I have copied the code below of the logic and was wondering whether anyone knew why the code cells would disappear?

I saw others asked this question but did not have much luck when I used their advice. Thank you!

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if(indexPath.row > myRatingsRestaurant.count-1){
            return UITableViewCell()
              }
        
            else {
                
            let cell = tableView.dequeueReusableCell(withIdentifier: "MyRatingsViewCell", for: indexPath) as! MyRatingsViewCell
            cell.tag = indexPath.row
            let myRatingRestaurant = myRatingsRestaurant[indexPath.row] //Thread 1: Fatal error: Index out of range
            cell.set(myRatingRestaurant: myRatingRestaurant)
            return cell
                
          }
    }

Solution

  • Per Apple documentation, cells are only loaded as they are shown in your screen for performance and allocate memory only as they are needed. cellForRow loads up the cell as they are scrolled to.

    There is something off with this logic below.

      if(indexPath.row > myRatingsRestaurant.count-1) {
           return UITableViewCell()
      }
    

    Let's say that you have 10 items in your table view. Once you scrolled to indexPath row 10. This logic indexPath.row > myRatingsRestaurant.count - 1 becomes true and returns an empty cell. As you scrolled down towards the end of your table view, these data points are returning an empty table view cell when they shouldn't.

    Assuming you conform to UITableView protocols numberOfRowsInSection should handle how many items to load in a table view and this logic should not be needed.