Swift 根据CollectionViewCell高度的动态Tableview单元格高度
在表视图单元格中有一个集合视图,在集合视图中有一个图像视图和一个标签。我的标签文本是动态的,显示我想根据我的集合视图单元格高度调整表格视图单元格高度 这是我的Tableview单元格代码 类TableViewCell:UITableViewCell{Swift 根据CollectionViewCell高度的动态Tableview单元格高度,swift,uitableview,Swift,Uitableview,在表视图单元格中有一个集合视图,在集合视图中有一个图像视图和一个标签。我的标签文本是动态的,显示我想根据我的集合视图单元格高度调整表格视图单元格高度 这是我的Tableview单元格代码 类TableViewCell:UITableViewCell{ @IBOutlet weak var collectionView: UICollectionView! var dyanmictext = "Hello How are u I am fine u say Hello How are
@IBOutlet weak var collectionView: UICollectionView!
var dyanmictext = "Hello How are u I am fine u say Hello How are u I am fine u sayHello How are u I am fine u say"
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
}
}
扩展TableViewCell:UICollectionViewDelegate、UICollectionViewDataSource、UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.image.image = #imageLiteral(resourceName: "4")
cell.textLabel.text = dyanmictext
let height = collectionView.collectionViewLayout.collectionViewContentSize.height
print(height)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenWidth = collectionView.frame.width
let textHeight = estimateFrameForText(text: dyanmictext)
let exactHeight = abs(textHeight.height)
return CGSize(width: screenWidth/2-10 , height:200+exactHeight-10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 1000
let size = CGSize(width: 200, height: height)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)]
return NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil)
}
}