iphone - 选中时选中的 UItableViewCell 保持蓝色

当我在用户选择 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];
}

正如我所说,如果您使用 UITableViewControllerUITableViewControllerviewWillAppear: em>没有看到这种行为,你应该检查你是否在你的类自己的 viewDidAppear: 中调用 super 实现。

更新(2013 年 10 月 30 日):嗯,这是一个流行的答案!正如 Ben 在评论中正确指出的那样,UITableViewController 实际上在 viewWillAppear: 而不是 viewDidAppear: 中执行此操作 - 这是正确的时机。此外,您可以使用 UITableViewController 的 clearsSelectionOnViewWillAppear 属性打开和关闭此行为。我已经修改了上面的答案以反射(reflect)这一点。

https://stackoverflow.com/questions/2803061/

相关文章:

objective-c - 如何在 Objective-C 中使用 Swift 字符串枚举?

iphone - 如何检查数组是空还是空?

objective-c - 所有异常断点在模拟器上无缘无故停止

iphone - NSCharacterSet:如何将 "_"添加到 alphanumericCha

objective-c - 如何本地化 iOS Storyboard

iphone - 在 UITableView 的 iOS 文档目录中列出保存的文件?

iphone - 如何在当前 UITableViewController 上方添加一个 UIView

ios - UILabel 根据要显示的文本自动调整大小

iphone - 绘制平滑曲线 - 所需方法

iphone - 在 bundle 中找不到名为 'Main' 的 Storyboard