user2722667
user2722667

Reputation: 8661

swift not sure on layoutIfNeeded setNeedsUpdateConstraints or updateConstraints setNeedsLayout

I am calling an API. Depending on what json data I get back I am modyfing my View Controller in viewDidLoad() in order to change my views design to display the given data best way possible.

What I do is to hide some uiViews and set their constraints to be .active = false but also changing some of the constraint by eg:

let noCButton = NSLayoutConstraint(item: aListTop, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: aListBottom, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
        view.addConstraint(noBidButton)

Then just before closing viewDidLoad() where I change/disable some constraints I call view.layoutIfNeeded()

So my question now is,

If I change/disable some constraints or hide a uiview, should I always call view.layoutIfNeeded() afterwards?

Also, do I need to call view.layoutIfNeeded() right after every change or can I just simply call it once before closing viewDidLoad()?

I dont get any errors in my console either way, but I just want to make sure I am doing it the right way. I also noted functions like updateConstraints but layoutIfNeeded seems to work, tho im not 100% sure about the difference

Thanks in advance,

Upvotes: 2

Views: 5620

Answers (1)

jervine10
jervine10

Reputation: 3077

I would call view.setNeedsUpdateConstraints(). After viewDidLoad(), viewWillLayoutSubviews() should be called automatically. This should be all you need to do at this moment.

If you need to force the view to update immediately call view.layoutIfNeeded(), if you want to make a set of changes and then have them all applied at the next layout pass just call view.setNeedsLayout() at the end of all your changes.

Upvotes: 3

Related Questions