Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCells don't deselect when returning from a segue

I have a UITableView with cells in a Storyboard, and a segue connecting the cells to another view.

When you select a cell it displays the cell selection animation (turning the cell gray, in my case) and pushes the other view onto the screen. But when you return to the tableview, the deselection animation doesn't show at all (the reverse of the selection animation). Since I'm just using a segue, I expected this to be taken care of by default.

Is there any way to force it to show the deselection animation?

like image 927
Evan Cordell Avatar asked Dec 16 '11 07:12

Evan Cordell


4 Answers

This would be handled automatically if your view controller was a subclass of UITableViewController and clearsSelectedOnViewWillAppear was set to YES (which is the default value).

In your case you can do this the same exact way that UITableViewController does it. Deselect the selected row in -viewWillAppear:.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    [self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
}
like image 165
Mark Adams Avatar answered Nov 18 '22 21:11

Mark Adams


Not sure about the use of segues but I often want to refresh data when a view controller appears. If you reload the table however, you clear the select row. Here is some code I use to maintain a selected row and show the deselect animation when returning. It may be the case that this may help you so I will post it here.

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
    [tableView reloadData];
    if(indexPath) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
    if(indexPath) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];  
    }
}
like image 24
Chase Avatar answered Nov 18 '22 22:11

Chase


Make sure you are calling the super implementations of the viewWill... and viewDid... methods

like image 11
John Estropia Avatar answered Nov 18 '22 20:11

John Estropia


For Swift 3

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(animated)
    if let path = tableView.indexPathForSelectedRow {

        tableView.deselectRow(at: path, animated: true)
    }
}
like image 5
AlQaim Solutions Avatar answered Nov 18 '22 21:11

AlQaim Solutions