Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update constraints swift layoutIfNeeded doesn't work

I need to update constraints (height of my CollectionView) when request is done and I have images from server, so height of View also will change.

Result screen

enter image description here

what I need screen

enter image description here

My code:

            DispatchQueue.main.async {
                self.cvActivity.alpha = 0
                self.collectionView.reloadData()
                self.collectionView.heightAnchor.constraint(equalToConstant: self.cellWidth * 2).isActive = true

                self.collectionView.setNeedsUpdateConstraints()
                self.collectionView.setNeedsLayout()
                self.view.layoutIfNeeded()
            }
like image 307

3 Answers

Well, basic idea by @J. Doe is correct, here some code explanation (for simplicity i used UIView, not UICollectionView):

import UIKit

class ViewController: UIViewController {

    @IBOutlet var heightConstraint: NSLayoutConstraint! // link the height constraint to your collectionView
    private var height: CGFloat = 100 // you should keep constraint height for different view states somewhere

    override func updateViewConstraints() {
        heightConstraint.constant = height // set the correct height

        super.updateViewConstraints()
    }

    // update height by button press with animation
    @IBAction func increaseHight(_ sender: UIButton) {
        height *= 2
        UIView.animate(withDuration: 0.3) {
            self.view.setNeedsUpdateConstraints()
            self.view.layoutIfNeeded() // if you call `layoutIfNeeded` on your collectionView, animation doesn't work
        }
    }

}

Result:

enter image description here

like image 161
pacification Avatar answered Oct 17 '22 08:10

pacification


Define a height for your collectionView, create an outlet from that constraint and increase the constant of that constraint and call layoutifneeded in an animation block

like image 23
J. Doe Avatar answered Oct 17 '22 09:10

J. Doe


You need to make object of your Height constraint from storyboard

 @IBOutlet weak var YourHeightConstraintName: NSLayoutConstraint!


  YourConstraintName.constant = valueYouWantToGive

---------OR--------

  collectionViewOutlet.view.frame = CGRect(x: 
    collectionViewOutlet.frame.origin.x , y: 
    collectionViewOutlet.frame.origin.y, width: 
    collectionViewOutlet.frame.width, height: 
    yourheightValue)
like image 36
Nilomi Shah Avatar answered Oct 17 '22 08:10

Nilomi Shah