【问题标题】:Cells Disappear when Scrolling a TableView (Swift)滚动 TableView (Swift) 时单元格消失
【发布时间】:2021-06-28 00:59:14
【问题描述】:

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

【问题讨论】:

  • 'return UITableViewCell()' 是什么意思?
  • @ElTomato 是在返回 Cells 时处理 default 的情况,而不是抛出异常,因为 UITableViewCell 是所有单元格的基础。这是 iOS 开发中非常常见的做法 :) 谢谢。

标签: swift tableview cell


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

    只是在这里建立最佳答案: 我知道您试图在那里进行错误检查,因此要进行错误检查,您应该使用 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
           }
    

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多