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?

+3


source to share


5 answers


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];
}

      

+4


source


Try this in your DidLoad view:



    [self setClearsSelectionOnViewWillAppear:NO];

      

+1


source


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.

+1


source


First, you need to reload the table view, select the row you want to specify, and then perform the deselection animation. The problem you are facing is the wrong procedure.

0


source


You can keep the current selection with

NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
[self.tableView reloadData];
[self.tableView selectRowAtIndexPath:selectedRow animated:NO scrollPosition:UITableViewScrollPositionNone];

      

0


source







All Articles