Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tableView.reloadData() ends other animations, how to fix it?

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?

like image 451
Fate Riddle Avatar asked Aug 30 '25 16:08

Fate Riddle


1 Answers

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 )

like image 140
Chathuranga Silva Avatar answered Sep 02 '25 06:09

Chathuranga Silva