Where is the best place for adding constraints programmatically? For custom views and for controllers too. Some people does this in init() method, other people use updateConstraints() (with flag which guarantees that constraints are added only once). I watched all WWDC videos and read all sample code from Apple but I'm confused because I can't find answer. Everybody does it differently. So what is the best approach for adding constraints from code?
Where is the best place for adding constraints in code?
Good question. I *want* to use updateConstraints, since they went to all the trouble of adding that whole infrastructure, but everything I've needed has been mostly in viewDidLoad or in IBAction type code that responds to user events. I usually change the constraints "at the source" as it were. I have one or two places where I do it in the rotation callbacks. I suspect those might be the best candidates for using the updateConstraints system but I haven't needed to yet (or I haven't seen the benefit of it yet, I guess).
I'm an OS X developer, but I think I can help you since Auto Layout works basically the same way on both platforms. It's perfectly fine to modify constraints anywhere (except in layout() or any similar methods that actually do the layout work). For example, I like to modify constraints in my action methods (you know, like swapping out detail views when the setting of a pop-up button is changed) or in my animation context completion handlers.
Or, if you really want to use updateConstraints, just call self.needsUpdateConstraints = true and updateConstraints will be called at the end of the run loop cycle. (This is great for performance because you can set the needsUpdateConstraints as many times as you wish and the actual work will only happen once.)
Do NOT use it in init() function.
Constraints must bind one or two views but it has not loaded in init() function.
Hi,
for me "viewDidLoad" is a good place to create and setup constraints to a initial state, because viewDidLoad is called only once and the views are garanteed to exist.
Second "updateConstraints" is the place where to take every dynamic thing into account. Eg. hiding or showing views depending on some state or changing the size of views depending on the parent view's size.
Dirk