1

I have two collection views in the same view and I would like to reduce the height of them, so that they adapt to the content size. However, the height should only reduce and never increase more than the initial value set in the storyboard. How can I accomplish this?

So far I have tried changing the collectionView height from the height costraint outlet everytime I would add new data but I don't get the right result. I tried changing it with this code:

self.deadlineCollectionViewHeight.constant = deadlinesCollectionView.collectionViewLayout.collectionViewContentSize.height

expected behaviour Wrong result

Luca Sfragara
  • 624
  • 4
  • 16
  • This may answer your question: https://stackoverflow.com/a/42438709/14437411 – Menaim Dec 19 '20 at 00:38
  • Have you tried adding self.view.layoutIfNeeded() just above self.deadlineCollectionViewHeight.constant = deadlinesCollectionView.collectionViewLayout.collectionViewContentSize.height ? – sudayn Dec 19 '20 at 05:00

2 Answers2

1

At what point are you trying to read the collectionViewContentSize value?

If you are doing that right after a reloadData() call - that might not give you accurate results because these calls are deferred to be executed at some point on main thread. The content size won't change immediately after doing the reloadData() call.

Try following :

  1. Declare a variable inside the class like this.
private var contentSizeObservation: NSKeyValueObservation?
  1. Start observing contentSize changes.
contentSizeObservation = deadlinesCollectionView.observe(\.contentSize, options: .new, changeHandler: { [weak self] (cv, _) in
    guard let self = self else { return }
    self.deadlineCollectionViewHeight.constant = cv.collectionViewLayout.collectionViewContentSize.height
})
  1. Do NOT Forget to clean this up in deinit call -
deinit {
    contentSizeObservation?.invalidate()
}

This approach will make sure that your collectionView is always as big in height as it's content.

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • Wau, thank you very very much. Worked like a charm! – Luca Sfragara Dec 28 '20 at 21:51
  • Your solution works as long as I don't change the collectionview datasource. If I have 0 deadlines and I a new one, deadlines content size is still 0 and the cell doesn't display. I posted another question: https://stackoverflow.com/questions/65587680/wrong-result-when-dynamically-changing-the-height-of-the-collectionview-to-adapt – Luca Sfragara Jan 10 '21 at 18:26
0

Add height constraint outlet then set it as you wish.

collectionViewheightConstraint.constant = modifierCollectionView.contentSize.height + 4
MMDev11070
  • 131
  • 5