微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据CollectionViewCell高度的动态Tableview单元格高度

如何解决根据CollectionViewCell高度的动态Tableview单元格高度

我在表格视图单元格内有一个集合视图,在集合视图内有一个图像视图和一个标签。并且我的标签文本是动态的,表明我想根据我的集合视图单元格高度调整表格视图单元格高度。

这是我的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 举报,一经查实,本站将立刻删除。