Reputation: 2319
I want to be able to call my UICollectionViewCell
class in the sizeForItemAtIndexPath
function. Like this:
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)
}
The problem is that cell.titleLabel.frame.size.height
, cell.subtitleLabel.frame.size.height
, and cell.thumbnail.frame.size.height
are all returning nil
. I assume this is because whenever sizeForItemAtIndexPath
is called, the cell has not loaded yet and cellForItemAtIndexPath
has not been called, yet.
I need to know this because the cell.titleLabel
can be multiple lines and widths which are set in the cellForItemAtIndexPath
.
Any idea?
Upvotes: 4
Views: 3327
Reputation: 24341
sizeForItemAt
is called before your cell
is actually created and configured with the required data. That is the reason you don't get correct data that you need.
Try this:
Create a dummy cell
in sizeForItemAt
by dequeuing
it from the collectionView
. Configure the cell with actual data that you want to display. After configuring it get what data you need, i.e.
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
}
Upvotes: 2