FRAMED: A UIView Category – Write Smarter Layout Code

Written by: on May 7, 2013

When you're building user interfaces in iOS, it's all about frames. And even simple layouts aren't always simple to implement.

Say you want to build a layout like this in code.  How would you do it?

Here’s one possibility:

This works, but it’s a bit clumsy; it takes some studying to figure out exactly how the frames are being manipulated, and it doesn’t read naturally.

Here’s an easier way:

Much better.  We’re now describing our view layout in far more expressive terms, and we’ve even trimmed out a few lines of code.

We’re able to do this by defining a category on UIView that exposes a set of new frame manipulation properties.  These properties serve as simple wrappers around UIView’s frame property, and getter and setter methods are defined for each of them.  They allow us to express frame manipulations on UIViews (and subclasses thereof) far more naturally, and with fewer lines of code.

The code for this category is available at this gist.  Snag it, drop it into your own projects, and let me know how it goes!

Chris Weathers

Chris Weathers

Chris is a lead software engineer at Possible Mobile, a high-end mobile development company. He has developed iOS apps since 2009. With a focus on front-end development, Chris has built the user interfaces for apps that have been featured on the App Store and garnered millions of downloads.

Add your voice to the discussion: