Search code examples
iosswiftxcodenslayoutconstraint

Can layoutIfNeeded be called only once per loading the view - e.g. viewDidLoad?


A view's height in my view controller needs to change as the user interacts with the application. Sometimes the view needs to be larger in height and other times it needs to be shorter depending on the number of options a user has.

I have implemented a method to change the height depending on the state of the view, and I call this method in viewDidLoad to set the initial state, and I recall the method whenever the state changes.

However, the only time the view actually updates the layout is from the call in viewDidLoad. All other calls of my method do not update the view.

func updateContainerViewHeight(constant: CGFloat) {
    print("lets update")
    baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    self.view.setNeedsLayout()

    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()
    }
}

FYI print("let's update") is printing in the console.


Solution

  • As here

    baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    

    every call adds new constraints which will cause conflicts , so create

    1-

    var baseCon,containCon:NSLayoutConstraint!
    

    2-

    baseCon = baseView.heightAnchor.constraint(equalToConstant: constant)
    baseCon.isActive = true
    containCon = containerView.heightAnchor.constraint(equalToConstant: constant)
    containCo.isActive = true
    

    3- Then play with constant

    baseCon.constant = ////