动态调整集合视图单元格的大小

问题描述 投票:0回答:1

我有一个更新的较旧的代码示例,但我仍然是新手,无法弄清楚如何解决此错误:

在具有集合视图的类中:

var array = ["Just testing this out"]

现在在UICollectionViewDelegateFlowLayout扩展中:

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

    let size = CGSize(width: 398, height: height)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.light)]

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

也:

private func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var height: CGFloat = 295
    //we are just measuring height so we add a padding constant to give the label some room to breathe!
     var padding: CGFloat = 14
    //estimate each cell's height
    if let text = array[indexPath.item].text {
          height = estimateFrameForText(text).height + padding
     }
     return CGSize(width: 398, height: height)    }

这是我得到错误的地方:

if let text = array[indexPath.item].text

这是集合视图单元格类中的UILabel,我不知道在哪里实现:

@IBOutlet weak var TextPosted: UILabel!
ios swift dynamic uicollectionview
1个回答
0
投票

您的测试阵列需要一些调整。尝试将其声明为可选(因为可能是从某处加载的实际数据)。

var array: [String]? = ["Just testing this out", "Another test"]

然后,此:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array?.count ?? 0
}

然后在collecitonView sizeForItemAtIndexPath函数中更新if语句:

if let text = array?[indexPath.item]{
}

在旁注中,我几天前写了一个开源extension来测量字符串大小。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.