我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
我正在编写一个带有tab视图中的表视图的iOS应用程序。在我的UITableViewController中,我实现了-tableView:didSelectRowAtIndexPath:,但当我在运行时选择一行时,该方法没有被调用。表格视图正在被填充,所以我知道控制器中的其他tableView方法正在被调用。
有没有人知道我到底搞砸了什么才让这一切发生的?
当前回答
在我的例子中,问题是将方法声明为private。
这并没有起作用:
private func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
这工作:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
其他回答
在我的案例中,解决方案是在下面的函数中将NO更改为YES。
iOS 9 +
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
一个常见的错误是编写调用selectRowAtIndexPath或deselectRowAtIndexPath的代码,并假设该调用将触发对委托的didSelectRowAtIndexPath的调用。但事实并非如此。
selectRowAtIndexPath和deselectRowAtIndexPath的文档清楚地说明:
"这些方法不会调用委托方法 tableView:willSelectRowAtIndexPath:或tableView:didSelectRowAtIndexPath:,也不会发出通知。"
听起来好像这个类不是表格视图的UITableViewDelegate,尽管UITableViewController应该自动设置。
你是否有机会将委托重置为其他类?
我不确定是否有人滚动到足够远的地方看到这个答案,但由于这是关于这个主题最受欢迎的问题,而答案并不在那里,我将添加它:
从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 }
}
以防你和我有同样的问题 显然,如果tableView处于编辑模式,这个方法不会被调用。你必须设置allowsSelectionDuringEditing为true。
通过这个问题:编辑时,' UITableView '不调用didSelectRowAtIndexPath ??