1

我希望能够在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.heightcell.subtitleLabel.frame.size.heightcell.thumbnail.frame.size.height都返回nil。我认为这是因为每当调用sizeForItemAtIndexPath时,该单元尚未加载,而cellForItemAtIndexPath尚未被调用。

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

有什么想法?

+0

也许这可以帮助https://stackoverflow.com/questions/30405063/setting-cell-height-of-collectionview-doesnt-really-expand-cell-滚动 – ryantxr

+1

您不应该使用'cellForItemAt:'以外的函数对某个单元格出队列即使您将某个单元格出列,您也不会得到一个填充了该索引路径值的单元格。您需要根据单元格的数据计算高度值,或者使用自动单元格高度并为您的单元格提供合理的'estimatedSize' – Paulw11

回答

0

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 
} 
相关问题