ios - 在 sizeForItemAtIndexPath 中调用 UICollectionView Cell

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我希望能够在 sizeForItemAtIndexPath 函数中调用我的 UICollectionViewCell 类。像这样:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let cell = MyCollectionViewCell()

    let itemHeights = cell.titleLabel.frame.size.height + cell.subtitleLabel.frame.size.height + 20 

    return CGSize(width: self.view.frame.size.width - 30, height: itemHeights + cell.thumbnail.frame.size.height)

}

问题在于 cell.titleLabel.frame.size.heightcell.subtitleLabel.frame.size.heightcell.thumbnail.frame .size.height 都返回 nil。我认为这是因为每当调用 sizeForItemAtIndexPath 时,单元格尚未加载并且尚未调用 cellForItemAtIndexPath

我需要知道这一点,因为 cell.titleLabel 可以是在 cellForItemAtIndexPath 中设置的多条线和宽度。

有什么想法吗?

最佳答案

sizeForItemAt 在您的 cell 实际创建并配置所需数据之前被调用。这就是您无法获得所需的正确数据的原因。

试试这个:

通过 dequeuingcollectionView 中创建一个 dummy cellsizeForItemAt 中。使用要显示的实际数据配置单元格。配置后获取您需要的数据,即

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    //Configure your cell with actual data
    cell.contentView.layoutIfNeeded()
    //Calculate the size and return
}

关于ios - 在 sizeForItemAtIndexPath 中调用 UICollectionView Cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45861553/

相关文章:

swift - NSCollectionViewItem 中的 IBOutlets 为零

swift - 将变量从 Gesture Recognizer 函数传递到 IBAction

ios - 在 UICollectionView 中终止异步 CGImageRef 加载

ios - 关于过去和 future 月份的问题

ios - 没有更多上下文swift4,表达式类型不明确

ios - Obj-c 协议(protocol)属性未在符合类中实现

xcode - 如何将私有(private)程序分发到 100 多个设备?

java - Java 中是否有类似于 Swift 的强引用循环(或类似的东西)的概念?

swift - 当我在 Swift 中使用 join() 方法时,不间断空格不起作用

UICollectionViewCell 在第一次出现时不会自动调整 subview 的大小