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

Cells Disappear when Scrolling a 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()
  }

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

假设您遵守 UITableView 协议 numberOfRowsInSection 应该处理在 table 视图中加载多少项目,并且不需要此逻辑。

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

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
       }