Frustrations with Auto Layout
I was working on a project from the Big Nerd Ranch book on iOS that involved adding an image to a view. I deployed it to my phone so that I could use the camera, and see how the view reacted. What ended up happening was every time I added an image to the view, it would expand and push the elements above it out of the view. I looked through the chapter I was working on, and couldn’t find what I was doing wrong. Then I went to the forums for the chapter, but I couldn’t find anything there.
The problem that I was running into has to do with constraints and frames, which is Xcode’s new way of letting you lay things out in a “device agnostic” manner. This is something that I had trouble with in iOS 6 a few months ago, and switching to 7 hasn’t made it any easier. I was really at loss for figuring out what was going on, and how to fix it.
After blindly clicking around the XIB for a while, I found a menu that offered to install the recommended frames and constraints. I still wasn’t clear on what that meant, but it sounded good, so I gave it a try. But still the image would kick everything out of the view. Finally, I unchecked the “use auto layout” box, and went back to the old school springs and struts to get everything to behave the way I wanted it too.
Fortunately, I’ve since made it to the chapter in the book which explains constraints and frames, and like all things Big Nerd Ranch, the book does a good job of breaking this down and explaining it. Now that I’ve worked through that chapter, I feel I have a better grip on constraints and frames.
The idea behind Auto Layout is to basically create a description of how you would like your view laid out, regardless of screen size or resolution. What I found is that the easiest way to do this is to find an element in your view that relates well to the view itself, like a toolbar that you’d like to be at the bottom, or a label you want anchored to a specific corner or side. You create a constraint to link that element where you want it, and then build constraints for other elements off of it. Once I understood what the constraints were trying to do, getting them to work correctly became a lot easier.