Reputation: 4235
Is it possible to include sizeForItemAt code to be dynamic based on cell class? I have a collectionView with a lot of rows with different types of cells, but not in any specific pattern (it would be difficult to type 'if index path.row == 29' and so forth for each cell).
I've tried variations of the below code, but it always returns the default value (else). The code snippet here has 3 types of cells (GroupCell, MatchingButtonsCell, and MatchingEventCell).
Can I make size dynamic based on Cell Class?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? GroupCell {
let cellHeight: CGFloat = (self.view.bounds.height * 0.55)
let cellWidth: CGFloat = self.masterCollectionView.frame.width
return CGSize(width: cellWidth, height: cellHeight)
} else if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? MatchingButtonsCell {
let cellHeight: CGFloat = 60
let cellWidth: CGFloat = self.masterCollectionView.frame.width
return CGSize(width: cellWidth, height: cellHeight)
} else if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? MatchingEventCell {
let cellHeight: CGFloat = 500
let cellWidth: CGFloat = self.masterCollectionView.frame.width
return CGSize(width: cellWidth, height: cellHeight)
} else {
let cellHeight: CGFloat = 10
let cellWidth: CGFloat = self.masterCollectionView.frame.width
return CGSize(width: cellWidth, height: cellHeight)
}
}
Thank you in advance!
Upvotes: 1
Views: 1442
Reputation: 534950
Can I make size dynamic based on Cell Class?
Basically no. The problem is that you are assuming at the time that sizeForItemAt
is called, there are "cells" where the items go. But that is not necessarily the case. For all you know, sizeForItemAt
is called before there are any "cells", when the collection view is still planning its layout.
That is why you are not given a cell in the call. You are given an index path. And that should be all you need. You need to be able to give the answer based on the index path, not on something about the "cell."
And that should be easy. After all, presumably you are setting the cell class in your implementation of cellForItemAt
— and you must be doing this based on the index path, because that is all the information you have. Well, if you can do it based on the index path there, do it based on the index path here.
Upvotes: 3