Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deselectRowAtIndexPath issue

I have just started working with tableViews, and I have 5 cells in a tableview in a viewController embedded in a navigationController. When a cell is pressed another view is pushed in. My problem is that the cell I press is selected but the selection doesn't go away. I have tried with this code:

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];

NewViewController *newViewController = [[NewViewController alloc] init];

newViewController.theTitle = [self.tableView cellForRowAtIndexPath:indexPath].textLabel.text;

[self.navigationController pushViewController: newViewController animated:YES];

}

The tableView is initialized in the viewDidLoad method.

Still when I click a cell the new viewController is pushed in but the cell stays selected. What might be the issue here?

like image 626
Wilhelm Michaelsen Avatar asked Oct 31 '13 22:10

Wilhelm Michaelsen


2 Answers

You've put your code in the didDeselectRowAtIndexPath - put it in the didSelectRowAtIndexPath. This is an easy mistake to make since didDeselect comes up in code completion before didSelect.

like image 146
Steve Avatar answered Sep 28 '22 14:09

Steve


Summary :

  • You have tableview that is in a ViewController that is in a NavigationController
  • Use touch a cell
  • A new ViewController is push on the NavigationController Stack
  • User hit back and goes back to the screen where you have a tableView

That is what I understand from your question.
At this moment the cell in your tableView should still be selected in order for the user to have a reminder of the last action he as done, but you also want it to get unselected animated at the point ( the mail application is a good example of this behaviour).

So the best place to deselect the cell in your tableView is in - (void)viewDidAppear:(BOOL)animated method of the UIViewController that have the tableview inside it's view. By doing so you will let the user a chance to see the selection before it gently fade away like in mail.

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:animated];
}

You can pass nil as argument of deselectRowAtIndexPath, tableView handles it gracefully.

like image 24
Vincent Bernier Avatar answered Sep 28 '22 14:09

Vincent Bernier