【问题标题】:App crashing when scrolling UITableView滚动 UITableView 时应用程序崩溃
【发布时间】:2017-07-26 12:04:32
【问题描述】:

我在表格视图中创建表格单元格,它们可以正确加载,您可以向下滚动它们,但如果您向上滚动应用程序会崩溃并显示错误 fatal error: Index out of range

这是生成表格单元格的代码

我对快速编码很陌生,所以请清楚你的答案

 public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return(tableRows.count)
    }

    var howmanyindex = 0

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ReviewControllerTableViewCell
        cell.label1.text = profilerComments[tableRows[howmanyindex]]
        cell.label2.text = String(profilerRatings[tableRows[howmanyindex]])
        howmanyindex += 1

        return(cell)
    }

【问题讨论】:

  • 不要手动处理索引。然后,您将不得不担心滚动的方向和所有内容,因此崩溃正在发生,因为当您向上滚动时,您的索引应该会减少,而这不会发生。直接使用 indexpath.row

标签: ios swift xcode uitableview


【解决方案1】:

问题似乎出在howmanyindex。由于您使用的是可重复使用的单元格,如果某个单元格超出屏幕的可见部分,cellForRowAt 将被多次调用以获取某个位置的单元格。

只需使用indexPath.row 来索引您的数据源数组。

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ReviewControllerTableViewCell
    cell.label1.text = profilerComments[tableRows[indexPath.row]]
    cell.label2.text = String(profilerRatings[tableRows[indexPath.row]])
    return cell
}

【讨论】:

    【解决方案2】:

    当 tableView 滚动您的 howmanyindex += 1 时,每个可见单元格都在增加,因此索引超出了 tableRows 数组,最好使用 tableRows 的 indexpath.row。

    【讨论】:

      【解决方案3】:

      无需手动跟踪表的索引howmanyindex,因为它可能与您的数据(或返回的计数)不同,因此当您从数组中获取数据时,它可能来自数组中的 nil 并且您 崩溃了。

      因此您可以从 indexPath.row

      获取当前单元格索引
      public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
              let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ReviewControllerTableViewCell
              cell.label1.text = profilerComments[tableRows[indexPath.row]]
              cell.label2.text = String(profilerRatings[tableRows[indexPath.row]])
      
              return(cell)
      }
      

      【讨论】:

        【解决方案4】:

        使用

        cell.label1.text = profilerComments[tableRows[indexpath.row]]
        

        代替

        cell.label1.text = profilerComments[tableRows[howmanyindex]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-21
          • 2012-12-07
          • 2016-08-28
          • 1970-01-01
          • 2018-01-16
          • 2011-07-10
          • 2011-12-26
          • 1970-01-01
          相关资源
          最近更新 更多