I am trying to figure out how to set AutoLayout constraints for a UICollectionView inside of a UIStackView (or without the StackView) and feel confused. The other answers on StackOverflow that I have found do not seem to directly apply.
Here is what I have:
-----------------------------------
| ----------------------------- |
| | UICollectionView # 1 | | (Sticky header for whole view)
| ----------------------------- |
| ----------------------------- |
| | UICollectionView # 2 | | (Table/grid with sections)
| ----------------------------- |
| ----------------------------- |
| | Button | |
| ----------------------------- |
| ----------------------------- |
| | UICollectionView # 3 | | (Sticky footer)
| ----------------------------- |
I am aware that there are now stick section headers for collection views, but collection #2 has it's own sections, so these are sticky headers for the whole view, which doesn't exist.
I can set constraints for views #1, #3, and the button, but #2's height is unknown. How do I set it so that view can dynamically change height, BUT view #3 is always visible.
I.e. View #2 will start to scroll if it becomes too long, and view #3 will stay visible.
If you want a self-sizing collection view, you have to create an NSLayoutConstraint for the collection view's height:
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
Then, in viewDidLayoutSubviews, update the height constraint and layout the view:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
view.layoutIfNeeded()
}
When you reload your collection view, make sure to call viewDidLayoutSubviews:
collectionView.reloadData()
viewDidLayoutSubviews()