具有动态单元格高度的Swift水平UICollectionView

时间:2019-10-04 07:33:00

标签: swift uicollectionview size height

我有一个水平collectionview,其基本大小是frame.width和330 height。我做了什么:

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

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

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

我尝试过为collectionview约束创建一个出口,并在cellForItem方法上对其进行更改,但看来这不是正确的方法。 如果重要的话,将集合视图放置在ScrollView中enter image description here

1 个答案:

答案 0 :(得分:0)

创建一个方法名称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)
    }