当我在用户选择 UITableView 行后推送 View 时,该行会突出显示蓝色,然后出现新 View 。没关系。但是当我“返回”时,该行仍然以蓝色突出显示。这是我的 didSelectRowAtIndexPath 代码。
- (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;
}
我做错了什么?
最佳答案
正如上面的答案所指出的,您需要明确取消选择该行。关于如何执行此操作,您有两种选择。第一种,是在选择后立即取消选择行:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
...
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
这会很好用,但是有一个替代方法,它是 UITableViewController
采用的方法,即保留选中的行,然后在 View 重新出现时取消选择它(在 Controller 之后你're push 会从堆栈中弹出)。
这有一点好处,即用户在返回时可以看到他们之前的选择,因此他们可以看到他们之前选择的内容。
要实现这一点,您只需要重写 viewWillAppear
:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
正如我所说,如果您使用 UITableViewController
和 UITableViewController
的 viewWillAppear:
em>没有看到这种行为,你应该检查你是否在你的类自己的 viewDidAppear:
中调用 super
实现。
更新(2013 年 10 月 30 日):嗯,这是一个流行的答案!正如 Ben 在评论中正确指出的那样,UITableViewController 实际上在 viewWillAppear:
而不是 viewDidAppear:
中执行此操作 - 这是正确的时机。此外,您可以使用 UITableViewController 的 clearsSelectionOnViewWillAppear
属性打开和关闭此行为。我已经修改了上面的答案以反射(reflect)这一点。
https://stackoverflow.com/questions/2803061/