Autolayout improvements

Ok, well not really improvements to auto layout on iOS, but improvements in my understanding of Auto Layout. The biggest thing I learned is that it is easier to setup and manage constraints in code, then to try and use Storyboards to define and modify the constraints.

If you have not used AutoLayout, Apple recommends that you start with doing it in Interface Builder. I find that this is not necessarily easier, and in my mind, it seems that using the code based method is much easier. The second thing I found was that the Visual Forma language is very powerful and easy to use. For example @”[self(<=128@800, >=64@800)]” indicates that the object has a minimum width of 64 points and maximum width of 128 points withe a priority of 800. You can set relationships between objects and to themselves. By doing this, you can setup very dynamic layouts that automatically resize and will adjust certain constraints over others. The priority, lower numbers == lower priority. 1000 is maximum priority and 0 is the minimum.

A great way of thinking about constraints is to think of constraints of the object on itself, then in relationship to things around it, and finally in regard to the entire view. If you’ve not watched the WWDC sessions from 2012 and 2013 on Autolayout, go watch them now! They are fantastic.

Experiences with Constraints and Storyboards

Well, it was a challenge, but I got it done. This past weekend I spent most of the time refactoring my personal app to using iOS 6.1’s autolayout capabilities. While I started off pulling out my hair, I ended the weekend with screens that looked pretty good, and that correctly handled almost everything I could throw at it. The net of all of this, is that I learned how to improve the flexibility of my apps. (I now can correctly re-size between iPhone 5 and pre-iPhone 5 layouts).

The biggest problem when going thru this, was that XCode kept trying to guess what I was trying to do. It would pin objects to the top of the screen, which would then disappear beyond the bottom of the screen when I rotated the screen. It would link two assets and then assume that I wanted the same spacing when I rotated, again pushing things around. The biggest thing I learned was to treat your screen layout like a bunch of sub-views. This allows you to then group things in subviews and build up relationships between the subviews. It reminded me of hand coding websites years ago, right after HTML introduced tables.

The other key thing to do, is make sure you pay attention to Less than, Equal, and Greater than. This impacts how things will grow or shrink. I cannot tell you how many times I caught myself with a Equal link(the default), when I wanted things to shrink down, a Less Than link. So far I have not gone into the details of code centric autolayouts, but for my simple app, I didn’t need that yet.

I can try and address questions if you have any, so drop a comment to the blog!