Skip to content
Tyler Fox edited this page Apr 21, 2014 · 13 revisions

Where to add constraints in code

If you're adding constraints from within a UIView subclass, you should do it in the updateConstraints method. If you're adding constraints from within a UIViewController subclass, you should do it in the updateViewConstraints method. Don't forget to call super from both! Also note that these methods may be called more than once during the lifetime of the object, so you'll usually want to keep a BOOL flag that lets you know once you have done your initial constraint setup (e.g. something like @property (nonatomic, assign) BOOL didSetupContraints; which you set to YES after the first time through the method so that you don't add duplicate constraints if it is called again).

Using UIView+AutoLayout together with Interface Builder constraints

You may want to use a combination of an Interface Builder file (nib/xib/storyboard) that specifies some constraints along with additional constraints added in code using the UIView+AutoLayout API. In general, this is a fine way of doing things.

Be aware that when using Xcode 5, you are allowed to have ambiguous layouts in Interface Builder, and at build time (without telling you) Xcode will automatically create and add in the necessary constraints to make your layout fully specified. This can cause problems for you at runtime if these auto-generated IB constraints end up conflicting with constraints you create and add in code.

To solve this issue, you'll need to create placeholder constraints for any ambiguous parts of your layout in Interface Builder. These placeholder constraints are removed from your layout at build time, and also prevent the auto-generated IB constraints from being added in their place. See this Stack Overflow answer for more info.

Debugging constraint issues

If you're having an issue with a constraint being broken due to a conflict (check your console output), one of the best ways to debug is to comment out constraints one-by-one until the issue disappears. (Alternatively, you can comment all the constraints out and add them back in one-by-one until the issue appears.) This will help you isolate the particular constraint(s) that are causing the problem.

Using Auto Layout in table views

Using Auto Layout within a UITableViewCell can be very powerful, but also very tricky to get right (and not have atrocious performance). I've written a nice post about this over at Stack Overflow which includes a high-level overview of the approach and some tips to get you started.

Learning more about Auto Layout

Check out the awesome Advanced Auto Layout Toolbox article over at objc.io by Florian Kugler. I promise it's worth the read.