I\'ve now updated three of my apps to iOS 7, but in all three, despite them not sharing any code, I have the problem where if the user swipes to go back in the navigation contro
This solution animates the row deselection along with the transition coordinator (for a user-driven VC dismiss) and re-applies the selection if the user cancels the transition. Adapted from a solution by Caleb Davenport in Swift. Only tested on iOS 9. Tested as working with both user driven (swipe) transition and the old-style "Back" button tap.
In the UITableViewController
subclass:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Workaround. clearsSelectionOnViewWillAppear is unreliable for user-driven (swipe) VC dismiss
NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
if (indexPath && self.transitionCoordinator) {
[self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[self.tableView deselectRowAtIndexPath:indexPath animated:animated];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
if ([context isCancelled]) {
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}];
}
}
I'm using
[tableView deselectRowAtIndexPath:indexPath animated:YES];
at the end of method
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Like this:
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//doing something according to selected cell...
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
You can try to set
self.clearsSelectionOnViewWillAppear = YES;
in a UITableViewController or
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];
in viewWillAppear, maybe before calling [super viewWillAppear:animated]; If your UItableView is not inside an UITableViewController you must deselect the cells manually:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Simple Swift 3/4 Answer:
override func viewWillAppear(_ animated: Bool) {
if tableView.indexPathForSelectedRow != nil {
self.tableView.deselectRow(at: tableView.indexPathForSelectedRow! as IndexPath, animated: true)
}
}