gpt4 book ai didi

ios - 在 sizeForItemAtIndexPath 中调用 UICollectionView Cell

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:03 25 4
gpt4 key购买 nike

我希望能够在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com