I have a UICollectionViewController
which generates cells with a random color for testing purposes. Now that the UICollectionViewController
is embedded in a UIScrollView
, I want the scrollView to be the same size as it's contentSize
.
I made a subclass of UICollectionView
, implemented intrinsicContentSize
method, and set the UICollectionView
's class to my custom class in IB. However intrinsicContentSize
never gets called. I have the exact same setup with an UITableView
and there it works flawlessly.
Any ideas on this?
- (CGSize)intrinsicContentSize {
[self layoutIfNeeded];
return CGSizeMake(UIViewNoIntrinsicMetric, self.contentSize.height);
}
Use this class to make UICollectionView update its intrinsic content size every time the content is changed.
Though, you should understand that if you embed it into another scroll view, cell recycling will not work. The most appreciated way to deal with nested collection view is described here.
The correct answer is to do something like this
And call -invalidateContentSize whenever you think it needs to change (after reloadData for example).
In Interface Builder you may need to set placeholder intrinsic size constraints to avoid errors.
This is subclassing and overriding of -intrinsicContentSize useful if you want to grow a collection view's frame until it is constrained by a sibling or parent view
I'm not sure why it's happening. Here's another solution to this problem. Set up a height constraint on
UICollectionView
object. Then set itsconstant
to be equal toself.collectionView.contentSize.height
. I use a similar approach in my app, though I've gotUITextView
instead ofUICollectionView
.UPDATE: I've found a way to do this with
intrinsicContentSize
: UITextView in UIScrollView using auto layout