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中自适应高度啦

你可能感兴趣的:(iOS tableViewCell嵌套UICollectionView 自适应高度)