user1615898
user1615898

Reputation: 1233

In a UIViewController, should I create manual autolayout constraints in viewDidLoad or viewWillLayoutSubviews?

In a UIViewController, should I create manual autolayout constraints in viewDidLoad or viewWillLayoutSubviews (or some other methods)?

Upvotes: 0

Views: 214

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

If you expect your constraints to be set up only once and expect it to be present through out the VC life cycle, create it in ViewDidLoad.

I have never came across a scenario, where you have to create/apply constraint in viewWillLayoutSubviews as viewWillLayoutSubviews gets called multiple times in a life cycle of VC and careless code might lead to same auto layout constraint being applied multiple times which will be perfect recipe for disaster if you try to update the constant value of the constraint later at some point.

Example :

If by mistake two similar constraints are added and if you aren't aware of it and hold the reference to only one constraint, on changing the constant value of it will cause other constraint to break. So viewWillLayoutSubviews isn't a great place to apply Autolayout constraint for me :) If you want to at any cost for some reasons, make sure you wont end up adding duplicate constraint.

or some other methods)?

This depends completely on your requirement, assume you want some constraints to be applied only under certain circumstance, in such cases you might either choose to create and apply constraint when needed or you might create all the constraint in viewDidLoad and then activate and deactivate those constraints on your need.

Upvotes: 1

Related Questions