Ios 滚动UITableView时应用程序崩溃

Ios 滚动UITableView时应用程序崩溃,ios,swift,xcode,uitableview,Ios,Swift,Xcode,Uitableview,我正在表格视图中创建表格单元格,它们加载正确,您可以向下滚动,但如果您向上滚动,应用程序会崩溃,出现错误致命错误:索引超出范围 这是生成表格单元格的代码 我很新的编码在swift,所以请明确你的答案 public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return(tableRows.count) } var ho

我正在表格视图中创建表格单元格,它们加载正确,您可以向下滚动,但如果您向上滚动,应用程序会崩溃,出现错误
致命错误:索引超出范围

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

我很新的编码在swift,所以请明确你的答案

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

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

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

因此您可以从
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)
}

问题似乎出在
howmanindex
上。由于您使用的是可重用的单元格,
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
}
使用

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

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

不要手动处理索引。然后,您将不得不担心滚动的方向和全部,因此会发生崩溃,因为当您向上滚动时,您的索引应该会减少未发生的索引。直接使用indexpath.row