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

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


当前回答

我刚刚找到了另一种不调用didSelect方法的方法。在某种程度上,可能是在func声明本身的一些错误中,XCode建议我将@nonobjc添加到我的方法中:

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

这将继续编译没有抱怨,但你永远不会被ui动作调用。

“那是我的两分钱,我想要回我的零钱”

其他回答

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

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.

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

一个常见的错误是编写调用selectRowAtIndexPath或deselectRowAtIndexPath的代码,并假设该调用将触发对委托的didSelectRowAtIndexPath的调用。但事实并非如此。

selectRowAtIndexPath和deselectRowAtIndexPath的文档清楚地说明:

"这些方法不会调用委托方法 tableView:willSelectRowAtIndexPath:或tableView:didSelectRowAtIndexPath:,也不会发出通知。"

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

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

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

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

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

这并没有起作用:

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

这工作:

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