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

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


当前回答

如果你在UITableView上添加了一个gestureRecognizer, didSelectRowAtIndexPath将不会被调用。

你需要使用gestureRecognizer委托方法来避免特定视图中的触摸。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isDescendantOfView:YourTable]) {
        return NO;
    }
    return YES;
}

其他回答

都是很好的答案,但还有一个需要注意……

(特别是当以编程方式创建UITableView时)

确保tableView可以通过设置[tableView setAllowsSelection:YES]来响应选择;或者删除任何将其设置为NO的行。

如果您所单击的单元格被突出显示,但函数仍然没有被调用,请再次检查函数的签名。它应该是这样的:

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

我遇到了一个问题,在几个月没有看我的代码后,我忘记了我实现了以下方法,由于一些不必要的需求

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath  *)indexPath{
    return NO;
}

为了使行被选中,它应该返回YES。

在这篇文章中有一些惊人的线索和答案(可能是我见过的最好的讨论之一!)这里的线索帮助我找出了我的问题,但我仍然花了很多时间在键盘上流口水,试图发现问题,这和其他帖子类似。然而,我最终发现它的方式有点不同,所以我想分享一下,以防其他人也遇到它。

事实证明,我的问题是,在代码中,一个超类添加了一个全屏的“错误视图”,它不是隐藏的,而是透明的。然而,因为它在tableview之上,“user action”被设置为YES,它拦截了我在tableview上的触摸。

我用Xcode很酷的“Debug View Hierarchy”按钮诊断了这个问题。下面是一个带有注释的屏幕截图,希望能解释我做了什么,以及我最终是如何诊断问题的。

在代码中,我只需要做:

errorMessageView.setUserInteractionEnabled = NO;
// or
errorMessageView.hidden = YES;

我的问题不在上面。太差劲了。但我想我应该把它列在这里,也许它能帮助到别人。

I have a tableViewController that is my "base" controller and then I create subclasses of this controller. I was writing all my code in the tableView:didSelectRowAtIndexPath routine in the "base" class. Completely forgetting that by default this routine had also been created (albeit with no code that did anything) in all of my subclasses as well. So when I ran my app, it ran the subclass version of the code, did nothing, and made me sad. So of course, once I removed the routine from the subclasses, it used mt "base" class routine and I'm in business.

我知道。别笑。但也许这能帮别人省下我浪费的一小时…