I've got an UICollectionView
with an UICollectionViewFlowLayout
, and i want to calculate its content size (for return in intrinsicContentSize
needed for adjusting its height via AutoLayout).
The problems is: Even if I have a fixed and equal height for all cells, I don't know how many "rows"/lines I have in the UICollectionView
. I also can't determine that count by the number of items in my data source, since the cells representing the data items vary in width, so does consequently the number of items I have in one line of the UICollectionView
.
Since I couldn't find any hints on this topic in the official documentation and googling didn't bring me any further, any help and ideas would be appreciated very much.
In case you are using Auto layout, then you could create a subclass of
UICollectionView
If you use the below the code then you don't have to specify any height constraints for the collection view as it would vary based on the contents of the collection view.
Given below is the implementation:
Swift version of @user1046037:
user1046037 answer in Swift...
At
viewDidAppear
you can get it by:Maybe when you reload data then need to calculate a new height with new data then you can get it by: add observer to listen when your
CollectionView
finished reload data atviewdidload
:Then add bellow function to get new height or do anything after collectionview finished reload:
And don't forget to remove observer:
Swift 3 code for user1046037 answer
In addition : You'd better calling
reloadData
before getting the height through :myCollectionView.collectionViewLayout.collectionViewContentSize