Mastering Auto Layout with EasyPeasy III: Relationships

Carlos Vidal
3 min readMar 2, 2017

--

With the material covered so far you must have a good understanding of how EasyPeasy works, its syntax and the fundamentals of Auto Layout. Relationships allow you to place or size views based on other views’ constraints. i.e. place a view 10px to the left of another view or set a width equal to another view’s width.

Position relationships

Relative position between button and header

In the screenshot above we have placed a button 20px under a header. To achieve this you only need to create a Top attribute with constant 20.0 and specify the relationship as follows:

As you can see the method .to(header) creates the relationship. Because both button and header are siblings, EasyPeasy automatically creates the relationship with the opposite attribute of Top for header, which is Bottom in this case. So, what if you want to create the relationship with other attribute of header?

The same but different

Now, the relationship is between the button Top attribute and the header Top attribute. The .to method accepts a second parameter allowing you to achieve this.

Dimension relationships

A not so stylized button

Now, our blue button looks a bit bloated, this is because we have specified a height equal to the header’s height.

We have achieved this using .like(header) along with the Height attribute. Likewise, this method also accepts a second parameter that allows you create this relationships with any other attribute of the reference view, in this case header.

Using multipliers

We are going to see how NSLayoutConstraint multipliers are set using EasyPeasy. To understand it, let’s think that we want the width of our button to be half of the header width.

The header is exactly 320px width whereas button is 160px.

As you can see, the Width attribute is created passing a CGFloat along with the custom prefix *, but how does it work?
Usually when you create an attribute like this Width(100.0), it creates a Constant struct with constant value 100.0 and a multiplier property with value 1.0. In this case, by setting *0.5 instead of 100.0, the resulting Constant struct has a constant value of 0.0 and a multiplier value of 0.5.

Coming soon…

In the next chapter of this series we will see how priorities work.

Apply here.

--

--