我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
当前回答
即使另一个答案已经被接受,我将为观察这个问题的人补充一个可能的问题和解决方案:
If you have automatic reference counting (ARC) turned on, you may find that even after assigning your controller as a delegate of the view, the view's messages to the controller are not being received because ARC is deleting the controller. Apparently the UITableView's delegate pointer does not count as a reference for the ARC, so if that is the only reference to it, the controller will be dealloc'd. You can verify whether or not this is happening by implementing the dealloc method on the controller and setting a breakpoint or NSLog call there.
解决方案是在其他地方使用强引用跟踪控制器,直到确定不再需要它为止。
其他回答
我刚刚有了这个,就像过去发生在我身上的一样,它没有工作,因为我在尝试添加方法时没有注意自动完成,我实际上最终实现了tableView:didDeselectRowAtIndexPath:而不是tableView:didSelectRowAtIndexPath:。
我看了所有的答案,非常同意。但我的情况完全不同。我为detailViewController创建了新的segue直接链接到StoryBoard中的表单元,这就导致了这个。我必须从我的单元格中移除那个segue并将它链接到UITableViewController本身。现在通过编写下面的代码,它可以工作,
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Do any operation
performSegue(withIdentifier: "DetailSegue", sender: self)
}
希望这个解决方案能帮助到那些有困难的人!
在我的情况下,问题是我有一个UITableViewCell子类,我实现了这两个方法: touchesBegan:withEvent: & touchesEnded:withEvent处理一个花哨的触摸动画。 但是我忘记添加[super touchesBegan: touchwithevent:event];方法ad [super touchesEnded: touchwithevent:event];也通知父单元的触摸。
所以将代码更改为以下解决了我的问题:
-(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
[super touchesBegan:touches withEvent:event];
//blah blah blah
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
//rest of the code
}
我也遇到过同样的问题。而且很难找到。但在我的代码中 是这样的:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
它必须返回indexPath,否则-tableView:didSelectRowAtIndexPath:没有被调用。
都是很好的答案,但还有一个需要注意……
(特别是当以编程方式创建UITableView时)
确保tableView可以通过设置[tableView setAllowsSelection:YES]来响应选择;或者删除任何将其设置为NO的行。