表视图 - cellForRowAt 中的索引超出范围

Ром*_*ров 0 uitableview ios swift

我在变量tableView.reloadData()内部调用。我只在函数中崩溃过一次,从来没有,从来没有在没有代码更改的情况下发生过。didSet{}itemscellForRowAt

override func tableView(_ tableView: UITableView, number ofRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return items.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.tag = indexPath.row
    let item = items[indexPath.row] //Thread 1: Fatal error: Index out of range
    cell.textLabel?.text = item.title
Run Code Online (Sandbox Code Playgroud)

Fay*_*med 6

可能的解决方案是您需要处理以解决崩溃。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if(indexPath.row > items.count-1){
        return UITableViewCell()
      }  
    else{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.tag = indexPath.row
    let item = items[indexPath.row] //Thread 1: Fatal error: Index out of range
    cell.textLabel?.text = item.title

    return cell
  }
}
Run Code Online (Sandbox Code Playgroud)

也许这会有所帮助。