TableView的didSelectRowAt方法未触发,请求排查问题
嘿,我看了你的代码,马上发现了一个关键问题,另外还有几个常见坑也帮你列出来,一步步排查就能解决啦!
最直接的错误:方法放错协议扩展了
你把didSelectRowAt写在了UITableViewDataSource的扩展里,但这个方法其实是**UITableViewDelegate协议**的方法!DataSource负责提供数据(比如行数、单元格内容),而Delegate负责处理交互事件(比如选中行、单元格高度等),这俩是完全不同的协议哦。
修复方法:
把didSelectRowAt移到UITableViewDelegate的扩展里,同时确保你的ViewController同时遵守这两个协议:
// 先确保ViewController明确遵守两个协议 class ViewControllerWaypoints: UIViewController, UITableViewDataSource, UITableViewDelegate { // ... 你的其他属性和方法 } // 拆分到对应协议的扩展中(更清晰) extension ViewControllerWaypoints: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return waypoint.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let waypoints = waypoint[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.accessoryType = .disclosureIndicator cell.isUserInteractionEnabled = true cell.textLabel?.text = waypoints.value(forKeyPath: "name") as? String return cell } } extension ViewControllerWaypoints: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("User selected cell....") // 你的点击处理逻辑 } }
还要检查这几个常见问题
即使方法放对了,还有可能导致didSelectRowAt不触发:
没有给tableView设置delegate:确保在代码里或者Storyboard/XIB里把tableView的delegate关联到你的ViewController。比如在
viewDidLoad里添加:override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self // 这行绝对不能忘! }如果是用Storyboard,右键tableView,把delegate选项拖到你的ViewController上即可。
tableView的
allowsSelection被设为false:这个属性如果是false,行是完全无法被选中的,自然不会触发事件。可以在代码里手动开启:tableView.allowsSelection = true单元格或父视图的交互被关闭:你代码里给cell设了
isUserInteractionEnabled = true,但要确保tableView本身的isUserInteractionEnabled也是true,同时没有其他覆盖在tableView上的透明视图(比如UIView)拦截了点击事件。自定义单元格的子视图拦截事件:如果用了自定义cell,检查一下cell内部有没有添加占满整个cell的子视图,并且这个子视图的
isUserInteractionEnabled设为了true——它会把点击事件全部吃掉,导致cell本身接收不到选中事件。
按照上面的步骤排查,应该就能解决didSelectRowAt不触发的问题啦!
内容的提问来源于stack exchange,提问作者prem111

