我希望能够在 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.height
、cell.subtitleLabel.frame.size.height
和 cell.thumbnail.frame .size.height
都返回 nil
。我认为这是因为每当调用 sizeForItemAtIndexPath
时,单元格尚未加载并且尚未调用 cellForItemAtIndexPath
。
我需要知道这一点,因为 cell.titleLabel
可以是在 cellForItemAtIndexPath
中设置的多条线和宽度。
有什么想法吗?
最佳答案
sizeForItemAt
在您的 cell
实际创建并配置所需数据之前被调用。这就是您无法获得所需的正确数据的原因。
试试这个:
通过 dequeuing
从 collectionView
中创建一个 dummy cell
在 sizeForItemAt
中。使用要显示的实际数据配置单元格。配置后获取您需要的数据,即
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/