How to determine height of UICollectionView with FlowLayout
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 your myCollectionView.collectionViewLayout
property and you get the height and width of the content as CGSize
. It's as easy as that.
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:
@interface DynamicCollectionView : UICollectionView
@end
@implementation DynamicCollectionView
- (void) layoutSubviews
{
[super layoutSubviews];
if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize]))
{
[self invalidateIntrinsicContentSize];
}
}
- (CGSize)intrinsicContentSize
{
CGSize intrinsicContentSize = self.contentSize;
return intrinsicContentSize;
}
@end
At viewDidAppear
you can get it by:
float height = self.myCollectionView.collectionViewLayout.collectionViewContentSize.height;
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 at viewdidload
:
[self.myCollectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld context:NULL];
Then add bellow function to get new height or do anything after collectionview finished reload:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//Whatever you do here when the reloadData finished
float newHeight = self.myCollectionView.collectionViewLayout.collectionViewContentSize.height;
}
And don't forget to remove observer:
[self.myCollectionView removeObserver:self forKeyPath:@"contentSize" context:NULL];
Swift 3 code for user1046037 answer
import UIKit
class DynamicCollectionView: UICollectionView {
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return contentSize
}
}