Menu & Search

Fastest way to use Auto Layout in code

June 10, 2016

Raise your ✋ if you hate adding views and setting up NSLayoutConstraints in code.

If your hand is in the air, you’re missing out on a great feature Apple introduced in iOS 9, which most developers don’t know about.

I’ll show you how to center a view in two elegant lines of code. But first, let me remind  you how this would look in the olden days:

At this point, you might say “Well mister, what about the Visual Format Language?”

Okay, let’s try that one as well:

Note: This doesn’t do exactly the same as the above constraints, but it should serve the purpose.

Ok, so now for the moment you’ve been waiting for. The magical two-liner:

Say whaaaat, right?

Ok, so where’s the catch. The things used in the last example are called Layout Anchors. You can read the full documentation on this sorcery on the official doc site, but it’s basically a factory class made by developers to make writing Auto Layout in code suck less.

Special note: When you’re using Layout Anchors, don’t forget to append the  .active = true !

Want to see more? Check out the Playground (Gist link) I’ve created to demonstrate a few use cases including the usage of constants, equal widths, margins, etc.

And remember – this is awesome and now you don’t have an excuse not to use Auto Layout if you’re dynamically building UIs in code!

STOP LOSING TIME WITH AUTO LAYOUT!

Take part in the 5-day course with actionable tasks that will let you become a master at recognizing and solving the most common mistakes iOS developers do with Auto Layout.

Let Auto Layout become a tool you swing with your utmost confidence!

I won't send you spam, I promise. Unsubscribe at any time. Powered by ConvertKit
Hey there! You're already subscribed to my newsletter and you've hopefully gotten some useful tips and tricks when working with iOS. If you're also working with Auto Layout, make sure to check out my book called Auto Layout Fundamentals and get a 20% off for being my subscriber! https://gum.co/autolayoutfundamentals/youareawesome
Jure Zove

A lot of things but mostly a programmer who really likes fast cars. Check me out on Twitter, if you fancy.

Related article

Introducing The “How do I Auto Layout” Cheatsheet

STOP LOSING TIME WITH AUTO LAYOUT! Take part in the…

Swift Optionals Demystified

STOP LOSING TIME WITH AUTO LAYOUT! Take part in the…

Self-sizing UITextView in a UITableView using Auto Layout (like Reminders.app)

I’ve covered dynamically sized UILabels in tables in a previous…

Type your search keyword, and press enter to search