简体   繁体   English

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

[英]Dynamically resizing collection view cell

I have this older code example that I updated but I am still a newbie and can't figure out how to fix this one error:我有这个更新的旧代码示例,但我仍然是新手,不知道如何解决这个错误:

In the class that holds the collection view:在包含集合视图的 class 中:

var array = ["Just testing this out"]

Now in the UICollectionViewDelegateFlowLayout extension:现在在 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)
}

Also:还:

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

This is where I get the error:这是我得到错误的地方:

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

And here's the UILabel from the collection view cell class I have no idea where to implement:这是集合视图单元格 class 中的 UILabel 我不知道在哪里实现:

@IBOutlet weak var TextPosted: UILabel!

Your test array needs some adjusting.您的测试阵列需要一些调整。 Try declaring it as an optional (since it likely will be with actual data loaded from somewhere).尝试将其声明为可选(因为它可能会与从某处加载的实际数据一起使用)。

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

Then this:然后这个:

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

Then update your if let statement in your collecitonView sizeForItemAtIndexPath function:然后在您的 collecitonView sizeForItemAtIndexPath function 中更新您的 if let 语句:

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

On a side note, I wrote an open-source extension to measure string size for things like this a few days ago.顺便说一句,几天前我写了一个开源扩展来测量字符串大小。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM