Four constraints, one view…

Constraints aren’t fun or flashy, but they have their purposes. There are times where I am unsure what to do, where to go. But I have a few steps and tricks I use constantly when I MUST work with constraints.

The first rule of thumb is: LESS IS MORE

When we look at what a frame is, there are four CGFloats. What are they exactly? The location of its x-axis, location of its y-xis, its width and finally its height. That is all the compiler needs to know to create a frame. That goes true for constraints too! If that is the case, why bother creating more constraints than needed if the compiler doesn’t care? Exactly! Absolutely no point.

When thinking about the constraints to add, think of the minimum required four constraints needed for that view. If you constrain the leading and trailing, ignore the width. Doing centerYAxis? Ignore top or bottom!

In a way, think of the constraints as a way of completing a frame. If you can do the math and figure out a EXACT frame from your four constraints, then you are good!

Second rule I set for myself is… : Don’t rely on others!

If I have a button on the left and its constrained to a button on the right, but they have no relevance, then why bother constraining them together? I wouldn’t unless they have some relationship to each other. I will usually default to constraining to the viewControllers view instead. That way the button’s constraints will not have a dependency on another button.

Third rule I set for myself is: Check constraints after updating frames!

Even after I click update frames and everything looks well and dandy, they still might be plotting to destroy my program! Check those constraints, make sure that bottom constrained to bottom IS what you wanted! Check for those 4 constraints, no more than needed.

As of this past week, my Fourth rule is: Scroll views and Stack views suck.

The scrollview follows the same rules of four constraints. However, stack views are an exception to this marvelous rule. The best ways to deal with them from my personal battles was to simply use the following 6 constraints for all stack views inside scroll views. Top, Bottom, Leading, Trailing, Height, Width.

No exceptions on those six! I’ve found working with stack views and scroll views a lot easier after follow the ironclad rule of 4–6.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.