Reputation: 4118
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?
Upvotes: 21
Views: 9671
Reputation: 69
For Swift 3
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let path = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: path, animated: true)
}
}
Upvotes: 5
Reputation: 1200
Better Swift update:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let path = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(path, animated: true)
}
}
Upvotes: 1
Reputation: 7434
Swift Update :-
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
if tableView.indexPathForSelectedRow != nil {
let indexPath: NSIndexPath = tableView.indexPathForSelectedRow!
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
Upvotes: 1
Reputation: 11191
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];
}
}
Upvotes: 11
Reputation: 17500
Make sure you are calling the super
implementations of the viewWill...
and viewDid...
methods
Upvotes: 11
Reputation: 30846
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];
}
Upvotes: 26