调用大小为UICollectionView的单元格forItemAtIndexPath
问题描述:
我希望能够在sizeForItemAtIndexPath
函数中调用我的UICollectionViewCell
类。就像这样:调用大小为UICollectionView的单元格forItemAtIndexPath
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
创建sizeForItemAt
一个dummy cell
。使用您要显示的实际数据配置单元格。配置它得到你所需要的数据,IE之后
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
}
也许这可以帮助https://*.com/questions/30405063/setting-cell-height-of-collectionview-doesnt-really-expand-cell-滚动 – ryantxr
您不应该使用'cellForItemAt:'以外的函数对某个单元格出队列即使您将某个单元格出列,您也不会得到一个填充了该索引路径值的单元格。您需要根据单元格的数据计算高度值,或者使用自动单元格高度并为您的单元格提供合理的'estimatedSize' – Paulw11