【问题标题】:Attempt to delete row 2 from section 1 which only contains 2 rows before the update尝试从第 1 部分中删除第 2 行,该部分在更新前仅包含 2 行
【发布时间】:2020-02-19 04:11:35
【问题描述】:

我正在尝试使用滑动操作删除 UITableView 中的一行,但一直收到以下错误:

'NSInternalInconsistencyException',原因:'试图从第 1 节中删除第 2 行,它只包含更新前的 2 行'

tableview 有多个部分。

代码如下:

override func numberOfSections(in tableView: UITableView) -> Int {
   return favouriteSubjectTitlesArray.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {    
   return favouriteCaseIDsBySubjectArray[section].count
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

    self.favouriteCaseIDsBySubjectArray[self.selectedSubjectID].remove(at: indexPath.row)
    DispatchQueue.main.async {
       self.tableView.deleteRows(at: [indexPath], with: .automatic)
      }
    }
return [unfavouriteAction]
  }
return nil
}

任何想法我哪里出错了?

【问题讨论】:

  • 存在不一致:在numberOfSections 中有favouriteSubjectTitlesArray,在numberOfRowsInSection 中有favouriteCaseIDsBySubjectArray 代表这些部分。数据源不喜欢不一致。你应该从indexPath.section删除
  • 好的,将尝试简化它。从indexPath.section删除是什么意思?
  • 您应该使用self.favouriteCaseIDsBySubjectArray[indexPath.section].remove(at: indexPath.row) 来确保您从正确的数组中删除

标签: ios swift uitableview


【解决方案1】:

终于找到解决办法:用struct更新datasource后,发现SwipeCellKit需要加上action.fulfill(with: .delete)

因此工作代码是:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
 if orientation == .left {
    //Unfavourite the case
    let unfavouriteAction = SwipeAction(style: .destructive, title: "Unfavourite") { action, indexPath in

        self.favouriteCases.remove(at: indexPath)

        self.tableView.beginUpdates()
        self.tableView.deleteRows(at: [indexPath], with: .right)
        action.fulfill(with: .delete)
        self.tableView.endUpdates()

   return [unfavouriteAction]
  }
return nil
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多