You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UITableView的didSelectRow方法无响应问题求助

UITableView点击Cell无响应问题修复

核心原因

你把tableView(_:didSelectRowAt:)方法放在了UITableViewDataSource扩展里,但这个点击回调方法属于**UITableViewDelegate协议**,不属于DataSource范畴,所以系统无法触发这个方法。

修复步骤

  1. 单独创建UITableViewDelegate扩展,把点击方法移到这个扩展里
  2. 确认你的ViewController已经设置了tableView的delegate:
    • 代码里可以在viewDidLoad中添加tableView.delegate = self
    • 或者在Storyboard/XIB里,把tableView的delegate关联到当前ViewController

修正后的完整代码

// MARK: - UITableViewDataSource
extension ChannelViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupResult.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let group = groupResult[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellContactNibName, for: indexPath) as! ContactCell
        cell.usernameLabel.text = group.name
        cell.messageLabel.text = group.recentMessage
        
        let storage = Storage.storage()
        let storageRef = storage.reference()
        let reference = storageRef.child("imagesFolder/\(group.image)")
        let placeholderImage = UIImage(named: "MeAvatar")
        
        // SDWebImage会异步设置imageView的image,无需手动重复赋值
        cell.uImage.sd_setImage(with: reference, placeholderImage: placeholderImage)
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension ChannelViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.row)!")
    }
}

额外优化提示

你原来代码里的cell.uImage.image = imageView.image是多余的,sd_setImage方法本身就会完成imageView的图片设置,不需要额外重复赋值。

内容的提问来源于stack exchange,提问作者Diogo Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:50:38