首页 > 解决方案 > 具有动态单元格高度的 Swift 水平 UICollectionView

问题描述

我有一个基本尺寸为 frame.width 和 330 高度的水平 collectionview。我做了什么:

1)放置一个collectionview并设置约束:前导 - 0,尾随 - 0,顶部 - 0,高度 - 330

2)然后将单元格大小设置为frame.width和height 330

3)但有时我的单元格有更多内容,所以我想将单元格扩展到 370

我尝试为 collectionview 约束创建一个出口并在 cellForItem 方法上对其进行更改,但似乎这不是正确的方法。如果重要,则将集合视图放置在 ScrollView 中在此处输入图像描述

标签: swiftuicollectionviewsizeheight

解决方案


创建一个方法名称estimateFrameForText,此方法将返回一个适合您的字符串的高度值!

private func estimateFrameForText(text: String) -> CGRect {
    //we make the height arbitrarily large so we don't undershoot height in calculation
    let height: CGFloat = 320

    let size = CGSize(width: yourDesiredWidth, height: height)
    let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]

    return NSString(string: text).boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
}

您必须像下面这样使用UICollectionViewDelegateFlowLayout和实现。sizeForItemAt[确保您的课程扩展UICollectionViewDelegateFlowLayout]

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset

         var referenceWidth: CGFloat = collectionView.safeAreaLayoutGuide.layoutFrame.width

         var referenceHeight: CGFloat = 320

       //we are just measuring height so we add padding constant to give the label some room to breathe! 
       var padding: CGFloat = <someArbitraryPaddingValue>

       //estimate each cell's height
       if let text = array?[indexPath.item].text {
           referenceHeight= estimateFrameForText(text).height + padding
       }

        return CGSize(width: referenceWidth, height: referenceHeight)
    }

推荐阅读