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.
Whoa! For some reason, after hours of research, I now found a pretty easy answer to my question: I was completely searching in the wrong place, digging through all the documentation I could find on
UICollectionView
.The simple and easy solution lies in the underlying layout: Just call
collectionViewContentSize
on yourmyCollectionView.collectionViewLayout
property and you get the height and width of the content asCGSize
. It's as easy as that.It's too late to answer this question but I have recently gone through this issue.
@lee's above answer help me a lot to get my answer. But that answer is limited to objective-c and I was working in swift.
@lee With reference to your answer, allow me to let the swift user get this issue solved easily. For that, please follow below steps:
Declare a
CGFloat
variable in declaration section: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:addObserver
to listen when yourCollectionView
finished reload data atviewWillAppear
:Then add bellow function to get new height or do anything after
collectionview
finished reload:And don't forget to remove observer:
I hope this will help you to solve your issue in swift.
Swift 4