【问题标题】:how to adjust UICollectonView height depend on label size如何根据标签大小调整 CollectionView 高度
【发布时间】:2017-05-23 11:08:01
【问题描述】:

在我的代码中,我创建了具有页眉和页脚的 UICollectonView。

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

文本可以从 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()
        }        
    }

【问题讨论】:

标签: ios swift uicollectionview


【解决方案1】:

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

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)
}

【讨论】:

    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多