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

UITableViewCell内嵌UICollectionView无法滚动不响应点击事件如何解决?

问题根因

你的代码存在三个核心问题导致UICollectionView无法响应交互:

  1. 未将UICollectionView添加到UITableViewCell的contentView容器中,而是直接添加到了cell本身,导致触摸事件被UITableViewCell默认拦截,无法传递到下层的UICollectionView。
  2. layoutSubviews方法漏调父类实现,可能导致子视图布局异常、交互可触区域错位。
  3. UITableView默认会延迟触摸事件传递,优先识别自身的滚动、点击手势,会抢占UICollectionView的交互事件。

修复步骤

第一步:修改UICollectionView的父视图与布局逻辑

修改CustomTableCellTableViewCell中的两处代码:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    // 改为添加到contentView而非cell本身
    contentView.addSubview(self.collection)
    self.collection.delegate = self
    self.collection.dataSource = self
}

override func layoutSubviews() {
    // 必须调用父类布局方法,原代码漏了这行
    super.layoutSubviews()
    // 以contentView的bounds为准设置collection的尺寸
    self.collection.frame = contentView.bounds
}

第二步:显式开启UICollectionView的交互属性

在UICollectionView的初始化闭包中添加如下配置,避免特殊场景下默认属性被修改:

private let collection: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.itemSize = CGSize(width: 128, height: 128)
    let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionCell")
    collection.backgroundColor = .systemBlue
    // 新增以下两行配置
    collection.isUserInteractionEnabled = true
    collection.isScrollEnabled = true
    return collection
}()

第三步:优化UITableView手势传递优先级

在PostViewController的UITableView初始化闭包中添加如下配置,关闭触摸延迟,让collection优先拿到手势事件:

private let table: UITableView = {
    let table = UITableView(frame: .zero, style: .grouped)
    table.register(CustomTableCellTableViewCell.self, forCellReuseIdentifier: CustomTableCellTableViewCell.id)
    table.register(UITableViewCell.self, forCellReuseIdentifier: "TableCell")
    // 新增以下一行配置
    table.delaysContentTouches = false
    return table
}()

完成以上修改后即可正常触发UICollectionView的横向滚动和didSelectItemAt回调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:45:04