我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。

有没有人知道我到底搞砸了什么才让这一切发生的?


当前回答

确保在主线程上调用reloadData。如果你从某种异步方法(例如:某种网络请求)调用该方法,表视图可能会或可能不会正确响应(在某些情况下,应用程序甚至会崩溃)。

使用主线程代码块来执行reloadData调用,如果调用是在其他一些方法块中进行的(你不确定):

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [tableView reloadData];
}];

其他回答

在我的情况下,didSelctRowAtIndexPath不调用是因为我在tableView的Selection属性中没有选择,设置为单一选择解决了我的问题

我在我的表视图上放了一个UITapGestureRecognizer来消除键盘,这阻止了didSelectRowAtIndexPath:被调用。希望它能帮助到别人。

另一个疯狂的可能性是:我在iPhone 5S上运行我的应用,我使用了:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

就像我过去一直做的那样。

然而,我没有仔细查看我的编译器警告…它说我应该把上面这一行改为:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

64位兼容性!摇动的拳头

当心,万一你开始扯你的头发。

在我的例子中,问题是将方法声明为private。

这并没有起作用:

private func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

这工作:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

我也遇到过同样的问题。而且很难找到。但在我的代码中 是这样的:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

它必须返回indexPath,否则-tableView:didSelectRowAtIndexPath:没有被调用。