-1

I'm trying to replicate an app design I saw on Dribbble (just for learning) and I have a question about dynamically changing a view's constraint. I have a collectionView, which might now contain cells at all.

Below that collectionView I have a view (UILabel), I want to change the UILabel topAnchor constraint, so if I have only one cell in the collectionView the UILabel will be displayed higher on screen. How can I do that? I have my View and ViewController separated, so when I set the constraints on the View file, there are no cells at all.

for example, In this state, I want the "To do list" label to be closer to the one cell I have:

https://imgur.com/Cwdmeu5

Jawad Ali
  • 11,075
  • 2
  • 25
  • 39
John Doah
  • 1,419
  • 3
  • 18
  • 34

1 Answers1

1

We don't have automatic dimension for UICollectionView, they only affect the UICollectionViewCell height. If you want to set the collection view height dynamically, I think the best way is to set the collection view height constraint equal to its content size after the collection view done loading. I mean something like,

collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height

then set your label at the bottom of your collectionView and set the maximum desired height collectionViewHeightConstraint can have

also this tutorial may help you Self sizing table view

write this code in viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
    myCollectionViewHeight.constant = height
    self.view.layoutIfNeeded()
}
Jawad Ali
  • 11,075
  • 2
  • 25
  • 39
  • 2
    It should be `collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height` – iOSArchitect.com Dec 31 '19 at 10:43
  • Thanks, where should I write it ? I tried to write it inside a function that gets called in the ViewDidLoad, I guess it won't work because the collectionView didn't finish loading when I get to the ViewDidLoad, but how can I know when it did finish loading? – John Doah Dec 31 '19 at 11:10
  • override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let height = myCollectionView.collectionViewLayout.collectionViewContentSize.height myCollectionViewHeight.constant = height self.view.layoutIfNeeded() } – Jawad Ali Dec 31 '19 at 11:14
  • Thank you! DidLayoutSubViews didn't work for some reason, but viewDidAppear did. – John Doah Dec 31 '19 at 11:23