I'm working on a todolist with nice animation when I delete a row by right swipe:
func toDoItemDeleted(toDoItem: ToDoItem) {
let index = (toDoItems as NSArray).indexOfObject(toDoItem)
if index == NSNotFound { return }
// could removeAtIndex in the loop but keep it here for when indexOfObject works
toDoItems.removeAtIndex(index)
// use the UITableView to animate the removal of this row
tableView.beginUpdates()
let indexPathForRow = NSIndexPath(forRow: index, inSection: 0)
tableView.deleteRowsAtIndexPaths([indexPathForRow], withRowAnimation: .Fade)
tableView.endUpdates()
// refresh gradient effect of rows
tableView.reloadData()
}
So basically I delete data, then make a remove animation with tableView.deleteRowsAtIndexPaths([indexPathForRow], withRowAnimation: .Fade)
, then I decide to fix the gradient effect of all existing rows(background color of rows, up to bottom from red to yellow, deleting a row breaks the gradient effect) by calling reloadData()
.
The result is reloadData()
happens too quickly before fade animation even begins, thus kills the animation. My questions are:
1. Why?
2. How to fix this?
You need to use animation block to achieve this one. Try this one :-
UIView.animateWithDuration(0.3, delay: 0,
options: [], animations: {
toDoItems.removeAtIndex(index)
// use the UITableView to animate the removal of this row
tableView.beginUpdates()
let indexPathForRow = NSIndexPath(forRow: index, inSection: 0)
tableView.deleteRowsAtIndexPaths([indexPathForRow], withRowAnimation: .Fade)
tableView.endUpdates()
// refresh gradient effect of rows
}, completion: { _ in
tableView.reloadData()
})
Set duration as you want.( 0.3 or what you want )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With