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

标签 swift uicollectionview size height

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

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

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

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

我尝试为 CollectionView 约束创建一个导出,并在 cellForItem 方法上更改它,但似乎这不是正确的方法。 如果重要的话,将 Collection View 放置在 ScrollView 中 enter image description here

最佳答案

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

关于具有动态单元高度的 Swift 水平 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58231843/

相关文章:

swift - 单击 UICollectionViewCell 打开另一个屏幕

ios - 具有流布局的水平滚动方向模式下的 UICollectionView 标题位置

ios - 如何在一个 collectionView 中使用多个项目数组?

html - 如何使 div/video 始终为浏览器窗口的大小,并固定在特定位置

Android:如何计算dp?

ios - 在两个方括号([])之间获取字符串是Swift 4

swift - 在 swift ( OS X ) 中从十六进制字符串获取 CGColor

ios - 如何使用 isPagingEnabled 自动滚动拖动垃圾箱更改 UIScrollView

css - 以像素为单位的最大允许高度,CSS

ios - Xcode 6 GM 种子无法启动 ios 模拟器