Normally a selected row in a UITableView
gets deselected with an animation when the user pops back from the detail view.
However, in my case where I have a UITableView
embedded in a UIViewController
I have to do it manually in viewWillAppear
like so:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// For some reason the tableview does not do it automatically
[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow
animated:YES];
}
Why is this and how to fix it?
When your main ViewController is from type UITableViewController, it has a property
clearsSelectionOnViewWillAppear
, which is per defaultYES
- so it will clear the selection automatically.This property is not available for an UITableView, i guess it's because it has no
ViewWillAppear
method either.A UIViewController doesn't need this property because it has no
UITableView
originally.conclusion: you'll have to implement it by yourself when you do not use a
UITableViewController
.Do the deselection in
didSelectRowAtIndexPath
instead ofviewWillAppear
:In swift, you can add the following lines in your
viewWillAppear
In swift 2, it's without parantheses:
In Swift 4 (and 3?) the function name was cleaned up:
I dont think deselecting the selected row is automatic... I normally do it before pushing to the next view
Nothing is wrong--deselecting the highlighted row is always "manual". If you look at Apple's sample code, you will see the same thing.
In Swift 3 / 4
If table view selections are not being cleared in a subclass of
UITableViewController
, despite the fact thatclearsSelectionOnViewWillAppear
is set to true, make sure to call the superclass version of[UIViewController viewWillAppear:animated]
if you override that method.If you fail to call the super version of that method, the value of
clearsSelectionOnViewWillAppear
will have no effect as the work of clearing the table view selection is actually performed inUITableViewController
's implementation ofviewWillAppear
.If your view controller does not inherit from
UITableViewController
you will need to clear the selection manually inviewWillAppear
.