I have a UICollectionView
with a header of type UICollectionReusableView
.
In it, I have a label whose length varies by user input.
I'm looking for a way to have the header dynamically resize depending on the height of the label, as well as other subviews in the header.
This is my storyboard:
This the result when I run the app:
Here's an elegant, up to date solution.
As stated by others, first make sure that all you have constraints running from the very top of your header view to the top of the first subview, from the bottom of the first subview to the top of the second subview, etc, and from the bottom of the last subview to the bottom of your header view. Only then auto layout can know how to resize your view.
The following code snipped returns the calculated size of your header view.
Swift 3
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout/1617702-collectionview
This drove me absolutely crazy for about half a day. Here's what finally worked.
Make sure the labels in your header are set to be dynamically sizing, one line and wrapping
Embed your labels in a view. This will help with autosizing.![enter image description here](https://i.stack.imgur.com/8KW0W.png)
Make sure the constraints on your labels are finite. ex: A greater-than constraint from the bottom label to the reusable view will not work. See image above.
Add an outlet to your subclass for the view you embedded your labels in
Invalidate the initial layout
Lay out the header to get the right size
You could achieve it by implementing the following:
The ViewController:
The custom
UICollectionReusableView
: