1.根据文字设定collectionViewCell的宽高:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let attributes = super.preferredLayoutAttributesFitting(layoutAttributes)
var frame = titleLabel.text!.boundingRect(with: CGSize(width: .max, height: 30), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:titleLabel.font ?? UIFont.systemFont(ofSize: 15)], context: nil)
frame.size.width += 10;
frame.size.height = 30;
attributes.frame = frame;
return attributes;
}
如果有其他控件,需要在frame里加上其他控件的宽高和间距
2.UITableViewCell 根据 UICollectionView 内容自适应高度:
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
let superSize = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
theaterCollectionView.layoutIfNeeded()
let size = theaterCollectionView.collectionViewLayout.collectionViewContentSize
return CGSize.init(width: superSize.width, height: size.height+superSize.height)
}
首先要在tableViewCell里正确添加约束,一定要确保约束能够撑开 tableViewCell 否则将会得到错误的高度44。
然后重写 systemLayoutSizeFittingSize:withHorizontalFittingPriority:horizontalFittingPriority: 方法。