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

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


当前回答

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

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

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

其他回答

在我的情况下,问题是我有一个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
}

记住在viewDidLoad方法中设置数据源和委托,如下所示:

[self.tableView setDelegate:self];

[self.tableView setDataSource:self];

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

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

如果您的表视图处于编辑模式(例如。[tableView setEditing:YES animated:NO];),你需要设置tableView。allowsSelectionDuringEditing = YES;

我刚刚有了这个,就像过去发生在我身上的一样,它没有工作,因为我在尝试添加方法时没有注意自动完成,我实际上最终实现了tableView:didDeselectRowAtIndexPath:而不是tableView:didSelectRowAtIndexPath:。