滚动 TableView (Swift) 时单元格消失

问题描述

我对 Swift 相当陌生,有点困惑。我已经对 Firestore 进行了编程以将数据加载到 TableView 中。但是,当我滚动 tableView 中的加载数据时,tableView 中的单元格消失了。我复制了下面的逻辑代码,想知道有没有人知道为什么代码单元会消失?

我看到其他人问了这个问题,但当我使用他们的建议时,运气并不好。谢谢!

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
                
          }
    }

解决方法

对于 Apple documentation,单元格仅在屏幕上显示时加载以提高性能,并且仅在需要时分配内存。 cellForRow 在单元格滚动时加载它们。

下面这个逻辑有问题。

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

假设您的表格视图中有 10 个项目。一旦您滚动到 indexPath row 10。此逻辑 indexPath.row > myRatingsRestaurant.count - 1 变为真并返回一个空单元格。当您向下滚动到表格视图的末尾时,这些数据点在不应该返回时返回了一个空的表格视图单元格。

假设您符合 UITableView 协议,numberOfRowsInSection 应该处理要在 table view 中加载的项目数量,并且不需要此逻辑。

,

只是建立在这里的最佳答案: 我知道您试图在那里进行错误检查,因此要执行错误检查,您应该使用 if-let 或 guard-let 语句,这基本上会检查是否有要显示的单元格。如果没有,那么您可以返回一个空单元格。

guard let cell = tableView.dequeueReusableCell(withIdentifier: "MyRatingsViewCell",for: indexPath) as! MyRatingsViewCell else {
   return MyratingsViewCell()
  }
        cell.tag = indexPath.row
        let myRatingRestaurant = myRatingsRestaurant[indexPath.row] 
        cell.set(myRatingRestaurant: myRatingRestaurant)
        return cell
       }