问题描述
按升序(从下到上)删除tableView行时,正在删除所选行上方的错误行。例如,有以下四行:
A 乙 C
相反,当按降序(从上到下)删除时,没有任何问题,行将按正确的顺序删除。基本的删除代码如下,tableView 有两个部分(在两个部分中按升序删除时会出现问题)。任何建议,非常感谢!
let deleteAction = UIContextualAction(style: .destructive,title: NSLocalizedString("Delete",comment:"Delete")) { _,_,complete in
let section = indexPath.section
let row = indexPath.row
let i = IndexPath(item: row,section: section)
if section == 0 {
self.cyclesteps.remove(at: row)
self.tableView.deleteRows(at: [i],with: .automatic)
let thesample = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceCycling)
let thepredicate = HKQuery.predicateForObjects(from: HKSource.default())
healthStore.deleteSamplesOfType(thesample!,predicate: thepredicate,withCompletion: { (success,count,error) -> Void in
dispatchQueue.main.async(execute: { () -> Void in
if error == nil
{
// saved successfully
//self.tableView.reloadRows(at: [i],with: .automatic)
}
else
{
print("Error occured while saving to Health Kit: \(error!.localizedDescription)")
}
})
})
}
解决方法
强烈建议先删除数据库中的项目,然后在数据源中(成功)然后更新视图
let deleteAction = UIContextualAction(style: .destructive,title: NSLocalizedString("Delete",comment:"Delete")) { _,_,complete in
guard indexPath.section == 0 else { complete(false) }
let thesample = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceCycling)
let thepredicate = HKQuery.predicateForObjects(from: HKSource.default())
healthStore.deleteSamplesOfType(thesample!,predicate: thepredicate,withCompletion: { (success,count,error) -> Void in
DispatchQueue.main.async {
if let error = error {
print("Error occured while saving to Health Kit: \(error.localizedDescription)")
complete(false)
} else {
// saved successfully
self.cyclesteps.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath],with: .automatic)
complete(true)
}
}
})
}
并且不要忘记调用操作的 complete
处理程序。