-
Notifications
You must be signed in to change notification settings - Fork 0
Tips and Tricks
If you're adding constraints from within a UIView subclass, you should override the -[UIView updateConstraints] method. If you're adding constraints from within a UIViewController subclass, you override the -[UIViewController updateViewConstraints] method. Don't forget to call super from both!
Note that both updateConstraints methods may be called more than once during the lifetime of the object, so in order to prevent re-creating and adding duplicate constraints you should keep a BOOL flag that lets you know once you have done your initial constraint setup. For example, @property (nonatomic, assign) BOOL didSetupConstraints; which you set to YES after the first time through the method, and use to guard your constraint setup code: if (!self.didSetupConstraints) { // setup initial 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 PureLayout 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.
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 in reverse order 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.
Don't forget to use the identifier property of constraints to set a human-readable description string. This can help greatly when you have a bunch of constraints in conflict, and you can quickly figure out which ones are which. See the iOS Demo 8 in the PureLayout Example project to see how these work.
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.
Check out the awesome Advanced Auto Layout Toolbox article over at objc.io by Florian Kugler. I promise it's worth the read.