Interface Builder Tip for Margin Constraints

If you are using Interface Builder to create constraints it can be a real pain dealing with margins. Sometimes you want to create constraints to a layout margin and sometimes you don’t. Here is a quick tip that makes that job less painful.

Constraint to Margin

Interface Builder has many (too many?) ways to create and edit constraints. I find myself mostly control-dragging between views and choosing the constraints from the popup menu rather than using the pin tool. For example, control-dragging in the document outline from a subview to the root view of a view controller gives you this:

This assumes I want to create constraints to the leading and trailing margins. What if I want constraints to the edges? It is a pain to have to edit the constraints in the inspector to remove the margins.

Hold Option for Alternates

The answer was staring me in the face, though to be fair it is difficult to spot:

I knew that you could hold the shift key to add several constraints without dismissing the menu. I never noticed you could hold down the ⌥ key to switch between using margins and edges. Here is the same menu with the ⌥ key allowing leading and trailing edge constraints:

It still needs some keyboard gymnastics to get the options I wanted. First the ⇧ key and then the ⌥ key to get the leading and trailing constraints without the margins. Then release the ⌥ key and choose the top layout guide and finally “Add Constraints”:

If you are not creating a constraint to the root view of a view controller Interface Builder assumes you do not want margins so you get edge constraints by default (control-dragging from yellow view to red view):

Holding down the ⌥ key this time switches to the container margins: