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

what I need screen

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()
            }
                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:

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
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With