Reputation: 113
I want to delete some cells in a table view with animation one by one, at first I use code like this:
[self beginUpdates];
[self deleteRowsAtIndexPaths:removeIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self endUpdates];
There are six indexPaths in removeIndexPaths array. It works in the right way, but the animation effect is 1. the six cells be empty,2. fade the empty area.
Then I try to delete them with for/while,like this:
int removeIndexRow = indexPath.row + 1;
while (item.level < nextItemInDisplay.level)
{
NSIndexPath *removeIndexPath = [NSIndexPath indexPathForRow:removeIndexRow inSection:0];
[items removeObject:nextItemInDisplay];
[self beginUpdates];
[self deleteRowsAtIndexPaths:@[removeIndexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"1");
sleep(1);
NSLog(@"2");
[self endUpdates];
}
In order to know how the function works, I use sleep and NSLog to output some flag. Then I find that the result is after outputting all the flags, the six cells been closed together, and the most unbelievable thing is that their animation like this:1.last five cells disappear with no animation, 2.the first cell be empty,3.fade the first cell empty area.
But what I want is delete cells one by one,first the first cell be empty and fade it,then the second, third...How can I solve it?
Upvotes: 1
Views: 1502
Reputation: 1936
The problem is that your loop (with the calls to sleep
inside it) is running on the UI thread. The UI won't update until you return control of the UI thread to the operating system, so that it can perform the necessary animations.
Try running this in a different thread, and making the calls to remove cells one by one on the UI thread. The code could look something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Now we're running in some thread in the background, and we can use it to
// manage the timing of removing each cell one by one.
for (int i = 0; i < 5; i++)
{
dispatch_async(dispatch_get_main_queue(), ^{
// All UIKit calls should be done from the main thread.
// Make the call to remove the table view cell here.
});
// Make a call to a sleep function that matches the cell removal
// animation duration.
// It's important that we're sleeping in a background thread so
// that we don't hold up the main thread.
[NSThread sleepForTimeInterval:0.25];
}
});
Upvotes: 3