问题描述
我在表格视图单元格内有一个集合视图,在集合视图内有一个图像视图和一个标签。并且我的标签文本是动态的,表明我想根据我的集合视图单元格高度调整表格视图单元格高度。
这是我的Tableview单元格代码 TableViewCell类:UITableViewCell {
@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,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView,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)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)