Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/118.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何根据标签大小调整UICollectionView高度_Ios_Swift_Uicollectionview - Fatal编程技术网

Ios 如何根据标签大小调整UICollectionView高度

Ios 如何根据标签大小调整UICollectionView高度,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,在我的代码中,我创建了UICollectionView,它有页眉和页脚 我的页脚高度应该是动态的,取决于文本大小 文本可以是1行到100行 这是我的密码 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

在我的代码中,我创建了UICollectionView,它有页眉和页脚

我的页脚高度应该是动态的,取决于文本大小

文本可以是1行到100行

这是我的密码

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width:collectionView.frame.size.width, height:50.0)
    }

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        switch kind {                        
            case UICollectionElementKindSectionFooter:
                let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SectionFooterCollectionReusableView", for: indexPath) as! SectionFooterCollectionReusableView

                footer.lblDescription.text = composition?.desc
                return footer


            default: return UICollectionReusableView()
        }        
    }

您可以向字符串扩展添加函数

extension String {

    func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin,
            attributes: [NSFontAttributeName: font], context: nil)
        return boundingBox.height
    }
}
然后在您的方法中计算文本高度

func collectionView(_ collectionView: UICollectionView,
    layout  collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
    if let string = composition?.desc {
        let height = string.heightWithConstrainedWidth(width, font: font)
        //calculate needed height
        return CGSize(width:collectionView.frame.size.width, height:neededHeight)
    }
    return CGSize(width:collectionView.frame.size.width, height:50.0)
}

设置
label.numberOfLines=0
,您是否熟悉
NSLayoutConstraints
/
nslayoutAcho
?和的可能重复