iOS tableViewCell嵌套UICollectionView 自适应高度

这个自适应高度有三个前提

  • 没有单独设置tableView的高度,设置成自动高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
  • 在设置collectionView的约束的时候,需要设置准确,确定约束到了四周,尤其是距离底部的约束
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        contentView.addSubview(collection)
        collection.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(20)
            make.right.equalToSuperview().inset(20)
            make.top.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().inset(20)
        }
    }
  • 在tableViewcell中重写systemLayoutSizeFitting方法
extension testCell {
    
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        
        let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
        
        self.collection.layoutIfNeeded()
        let height = self.collection.collectionViewLayout.collectionViewContentSize.height
        return CGSize(width: size.width, height: size.height + height)
    }
}

完成以上三步,就可以实现collectionView在tableview中自适应高度啦

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容