Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

iphone - Selected UItableViewCell staying blue when selected

When I push a view after a user has selected a UITableView row, the row gets a blue highlight, and then the new view appears. That's fine. But when I go 'back' the row is still highlighted in blue. Here's my didSelectRowAtIndexPath code.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingsViewController *controller = [[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:nil];
    [[self navigationController] pushViewController:controller animated:YES];
    [controller release], controller = nil; 
}

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As the answers above point out, you need to explicitly deselect the row. You have two options as to how you do this. The first, is to deselect the row immediately after selection:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  ...
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

That will work just fine, but there is an alternative, and its the approach taken by UITableViewController which is to leave the row selected then deselect it when the view re-appears (after the controller you're pushing is popped off of the stack).

This has the slight advantage that the user sees a glimpse of their previous selection when they return so they can see what they had selected previously.

To implement this, you just need to override viewWillAppear:

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

As I said, this is what the default of implementation of UITableViewController's viewWillAppear: does so if you are using UITableViewController and not seeing this behaviour, you should check that you are calling the super implementation in your class' own viewDidAppear:.

Update (30 Oct 2013): well, this is a popular answer! As Ben rightly points out in the comments, UITableViewController actually does this in viewWillAppear: not viewDidAppear: - this is the correct timing. In addition, you turn this behaviour on and off using the clearsSelectionOnViewWillAppear property of UITableViewController. I've amended my answer above to reflect this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...