我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
当前回答
我也遇到过同样的问题。而且很难找到。但在我的代码中 是这样的:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
它必须返回indexPath,否则-tableView:didSelectRowAtIndexPath:没有被调用。
其他回答
另一个可能的原因是UITableView被嵌入到UIScrollView中。我今天遇到了这个问题,因为我无意中使用了滚动视图而不是普通视图作为控制器的根视图。
我不确定是否有人滚动到足够远的地方看到这个答案,但由于这是关于这个主题最受欢迎的问题,而答案并不在那里,我将添加它:
从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 }
}
注意故事板中的UITableView属性,在我的例子中发生的是,我在故事板中选择了combox为“Selection: Single Selection”,这不允许didSelectRowAtIndexPath方法运行。
tableView?.allowsSelection = true
在Xcode 11.7中默认为False
我在我的表视图上放了一个UITapGestureRecognizer来消除键盘,这阻止了didSelectRowAtIndexPath:被调用。希望它能帮助到别人。