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

UITableViewCell动态高度实现:内嵌UICollectionView展示全部标签无需滚动

实现UITableView嵌套UICollectionView的Cell动态高度方案

你已经完成了基础配置:行高返回UITableView.automaticDimension、关闭UICollectionView的滚动属性,接下来按以下步骤补充配置即可实现需求:


1. 完善UICollectionView的Auto Layout约束

  • 将UICollectionView的上、下、左、右四个边距,完整约束到UITableViewCell的contentView对应边
  • 不要给UICollectionView添加固定高度、固定高宽比约束,允许它的高度由自身内容大小撑开

2. 自定义自撑高的UICollectionView子类

系统默认UICollectionView不会主动把内容大小同步给Auto Layout,需要重写相关属性实现自适配:

class SelfSizingCollectionView: UICollectionView {
    override var contentSize: CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }
    
    override var intrinsicContentSize: CGSize {
        // 如果设置了contentInset,需要把边距也加上
        // return CGSize(width: contentSize.width + contentInset.left + contentInset.right, 
        //               height: contentSize.height + contentInset.top + contentInset.bottom)
        return contentSize
    }
}

将你项目中Cell内嵌的UICollectionView的类,改为上面自定义的SelfSizingCollectionView即可。


3. 补充UITableView的自动高度配置

除了在heightForRowAt返回自动尺寸,还要添加行高估算配置:

// 在UITableView初始化处添加以下代码
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100 // 填入和你业务Cell平均高度接近的估算值即可

4. 数据刷新后触发高度更新

每次给UICollectionView赋值数据源、调用reloadData之后,需要通知父UITableView更新对应行的高度:

collectionView.reloadData()
collectionView.layoutIfNeeded()
// 刷新行高,不需要reload整行,避免界面闪烁
tableView.beginUpdates()
tableView.endUpdates()

注意事项

  • 如果你使用UICollectionViewFlowLayout,要确保cell的尺寸计算逻辑正确;iOS14及以上版本使用UICollectionViewCompositionalLayout配合自动尺寸规则适配更简单
  • 如果UICollectionView设置了contentInset内边距,需要在重写intrinsicContentSize时把边距值加到返回的尺寸里,避免内容显示不全

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:27:06