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

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


当前回答

我不确定是否有人滚动到足够远的地方看到这个答案,但由于这是关于这个主题最受欢迎的问题,而答案并不在那里,我将添加它:

从Xcode 9 / Swift 4开始,所有Objective-C方法都应该标记为@objc。编译器做了一个合理的工作,识别它应该应用在哪里,但它不计算继承。例如:

class Delegate: NSObject, UITableViewDelegate {
}

class SuperDelegate: Delegate {
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath }
}

这将不会产生任何警告、崩溃或构建错误。但是你的行不会被调用,直到你添加@objc:

@objc class SuperDelegate: Delegate {
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath }
}

其他回答

听起来好像这个类不是表格视图的UITableViewDelegate,尽管UITableViewController应该自动设置。

你是否有机会将委托重置为其他类?

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

这并没有起作用:

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

这工作:

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

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

这些答案对我都没用。大约一个小时后,我发现了一些非常阴险的事情:

我在另一个表格视图的单元格中有一个表格视图。我决定创建一个包含内部表视图的封闭视图。我将这个视图命名为contentView并在xib中连接它。

UITableViewCell已经有一个contentView并对它做了一些奇怪的事情。当我将属性重命名为mainContentView并将视图重新连接到这个重命名的属性时,问题自行解决了。

我重复了之前所有的答案,但没有一个对我有帮助。经过反复试验,我找到了一个不同的解决方案。我有一个UIImageView覆盖整个单元格(作为背景)。默认情况下,UIImageView禁用用户交互。通过启用imageviews用户交互委托方法-didSelectRowAtIndexPath:再次被调用。 如。

cell.imgView.userInteractionEnabled = YES;