提问者:小点点

按升序(从下到上)删除tableView行时,会删除不正确的tableView行


按升序(从下到上)删除tableView行时,正在删除所选行上方的不正确行。例如,使用以下四行:

A B C D

当向左滑动删除D行时,正在删除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)")
                            
                            
                        }
                    })
               })
                
            }

共1个答案

匿名用户

强烈建议首先删除数据库中的项,然后删除数据源中的项(如果成功),然后更新视图

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处理程序。