TableView reloadData and deselectRowAtIndexPath
I am using the following code to deselect a cell of a selected table view when returning back to the table view in -viewWillAppear:animated
.
[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
I also need to reload the table view data in this case, but when you do, it will clear the selected state of the selected cell so that you don't see the fade out animation.
Is there a way to reload the table data and also keep the selected state to create the deselection animation?
source to share
After several tries, I found something that works. You need to set the deselection after a "delay" (0 seconds) to make sure it happens on the next draw cycle and animates correctly.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
[self.tableView reloadData];
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
[self performSelector:@selector(deselectRow) withObject:nil afterDelay:0];
}
- (void)deselectRow
{
[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
}
source to share
The obvious solution suggested by @ user2970476 seems to work fine on iOS 7. For iOS 8, I slightly modified @ Stonz2's answer to use blocks
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_async(dispatch_get_main_queue(), ^(void) { // necessary for iOS 8
[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
});
}
I also had to set self.clearsSelectionOnViewWillAppear = NO;
to viewDidLoad
, because the IB value was being ignored.
source to share