Reputation: 32140
I am in a loop with myself on from where to get the cell's size in a collection view in case I have a cell with auto layout
I understand that sizeForItemAtIndexPath
should get the size from the data and not from the cell itself, because the cell is not drawn yet, but in auto layout I can't calculate this just by looking at the data, unless I put in code the contraints in a way that I can later calculate from them (seems crooked)
On the other hand, UIView does have intrinsicContentSize
and systemLayoutSizeFittingSize
which gives the size of a view that's already drawn or going to be drawn.
But in sizeForItemAtIndexPath I don't have a view yet, and the data is just data.
the cell nib looks like this
In what way should I get the size of a custom cell (from .nib)?
I could technically hard code sizes for the images and icons, but that feels wrong. It also feels wrong to ask the view what size it is in a function that should tell the controller what size it is
Upvotes: 3
Views: 3203
Reputation: 8014
You can use an off screen prototype cell which you configure and then use to determine its size.
This is a common approach for UITableView pre iOS8 to determine cell height. The same approach should work for UICollectionView.
See the accepted answer here: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
Upvotes: 2