Search code examples
iosautolayout

How to set standard spacing between UIViews in code with auto layout?


In interface builder I can get a "Vertical Space" that matches the "standard" spacing by 'pinning':

enter image description hereenter image description here

In the visual constraint language I can accomplish the same thing with:

V:[top]-[bottom]

How do I add standard spacing between two views in code?

I'm looking for something like this that might appear in a UIViewController:

NSLayoutConstraint *spacing = ???
[self.view addConstraint spacing];

Solution

  • Mixing and matching visual format constraints and the more verbose single constraint creation style (what I think you are referring to when you say "in code") is fine - in fact, in the WWDC talks about auto layout, the "preferred" order for you to create constraints was stated as:

    • Interface builder
    • Visual format
    • Single constraint style

    Unless you need the extra power and flexibility that the single constraint style gives you (and there are lots of places where visual format doesn't work, in my experience with it so far), you should use the visual format. It sounds like you're approaching the list above from the bottom up, instead of the top down.

    If you want to lay out views with standard spacing, and you're not using IB, then the visual format would make sense to use. As Rob says, there isn't a constant for "standard" spacing available, and you're making much more work for yourself by insisting on single constraints for everything.