[英]Deleting a cell from UITableView in Swift
從tableView刪除單元格時,動畫運行良好,但不會重新加載tableView數據。 我嘗試在沒有.beginUpdates()
和.endUpdates()
情況下運行,而是使用.reloadData()
,該過程有效,但動畫無效。
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
context.deleteObject(coreData[indexPath.row] as NSManagedObject)
coreData.removeAtIndex(indexPath.row)
do {
try context.save()
} catch {
print("Error deleting NSManagedObject")
}
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tasks.removeAtIndex(indexPath.row)
names.removeAtIndex(indexPath.row)
ids.removeAtIndex(indexPath.row)
tableView.endUpdates()
// remove the deleted item from the `UITableView`
default:
return
}
}
順便說一下, tasks
數組是tableView的主要數據。
如何使用平滑刪除動畫在刪除單元格時重新加載數據?
要考慮的兩件事:
在更新表視圖之前,必須先更新數據模型。 因此,代碼的順序必須為:
tasks.removeAtIndex(indexPath.row) names.removeAtIndex(indexPath.row) ids.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
無需進行begin/endUpdates
因為您只需進行一次調用即可更新表視圖。
將所有removeAtIndex...
行移動到beginUpdates
之前,必須先從數據中刪除對象,然后才能刪除行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.