Thursday, June 21, 2012

Autolayout: Don't Fight It

Note: This blog is deprecated. @synthesize zach has moved to a new home, at zpasternack.org. This blog entry can be found on the new blog here. Please update your links.

TaskLog is the first app I've developed which uses the new Cocoa Autolayout introduced in Mac OS 10.7 Lion.

I first used it in TaskLog's log view, shown below: Task Log screenshot

As you can see, there are quite a few UI elements in there. But all I did was put them where I wanted them, and Autolayout figured it all out. I didn't have to configure a single thing, it all Just Worked™.

Now at some point I decided to make TaskLog's main view resizable (so that the entire window resizes to perfectly fit the text of the current task). And that's where Autolayout became a real headache. In this view, there are actually a lot of overlapping UI elements which are shown or hidden depending on what the state of the UI. For example, when you hit "Start a new task", a bunch of the UI is hidden, and a text entry field and Start/Cancel buttons are displayed. TaskLog main view screenshot 2

Then when you hit Start, those are hidden and a bunch of other views are displayed. TaskLog Main window screenshot

I wanted some of the views to be anchored to the bottom of the window, some to be anchored to the top, and a few to be anchored to both top and bottom and resize vertically. More importantly, Autolayout was having none of this. I spent an entire day adding my own constraints to try to get the behavior I was after, and in the end I wasn't able to get it to work that way I wanted.

Then I had an epiphany: give up. It turns out that springs and struts can totally do what I needed to do in the main view UI; there was no compelling reason to use Autolayout. I turned it off, set up some springs and struts, and went on my merry way.

Now, don't get me wrong, Autolayout is amazing. It allows you to do incredibly complicated layout with little to no effort. However, my advice is this: if you find yourself fighting Autolayout, stop and think about what you're trying to do. If what you're trying to accomplish can be done with springs/struts, and/or Autolayout isn't making your life better, simply turn it off for that view.

The Autolayout session from last year's WWDC is an awesome intro to Autolayout. I'd definitely recommend giving that a view if you haven't already.

No comments:

Post a Comment