首页 > 解决方案 > 滚动 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
                
          }
    }

标签: swifttableviewcell

解决方案


根据 Apple文档,只有在屏幕上显示单元格时才会加载它们以提高性能,并仅在需要时分配内存。cellForRow当它们滚动到时加载单元格。

下面这个逻辑有些不对劲。

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

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

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


推荐阅读