Auto Layout Bug with the Top Layout Guide for Xcode 5

Update (3/14/14): Xcode 5.1 fixes this bug. When you drag to the top it'll add the appropriate top constraint and won't send your views offscreen or offset them incorrectly.

I do a lot of UI work in Xcode 5 with Interface Builder. I'm building class materials and this is a very common bug, that I didn't figure out a good solution until now. These types of bugs can make Auto Layout very frustrating to learn because it doesn't behave like you might expect. I'll describe the bug below, the solution, and a video solution for the curious.

Top Layout Guide Bug

If you add a view to a .storyboard or .xib file, you can align it to the top edge or just under the status bar. This edge under the status bar in Xcode 5 is called the Top Layout Guide. The guide is a helper for setting up constraints, but unfortunately it doesn't work as you might expect most of the time.

When you Right-click + Drag (Ctrl + Left-click + Drag) to add constraints to the Top Layout Guide it'll add the wrong constraint and your iPhone app layout will not be what you expect.

The layout doesn't match what we would expect. Label is squashing our status bar text!

The layout doesn't match what we would expect. Label is squashing our status bar text!

Instead of adding a constraint from the top of the view to the Top Layout Guide, it adds a constraint from the bottom of the view to the Top Layout Guide. For some reason this creates a constraint that pushes your view upwards and it conflicts with the status bar, or it'll go above the status bar.

Solution

The work around is to use the Menu bar options to add the constraint using the Pin menu. You can't add the constraints with the Right-click + Drag menu. Note: Delete any previous constraints to the Top Layout Guide, or the steps below won't help.

Editor > Pin > Top Space to Superview

Pin the Top Space to the Superview and you'll fix your bug.

Pin the Top Space to the Superview and you'll fix your bug.

After we add the Pin to the superview, we'll have to add all the normal constraints. You should see the following constraints (visually) if you look at the top view.

Correct Auto Layout Constraints for the Top Layout Guide

Correct Auto Layout Constraints for the Top Layout Guide

4 Layout Constraints to specify the size and position 

4 Layout Constraints to specify the size and position 

Using the new layout, the label will appear on the iPhone Simulator in the correct spot, and so will the red UIView. Now using this powerful tip you can make your app match your design.

Proper Auto Layout for a UIView that is near the top of an iPhone.

Proper Auto Layout for a UIView that is near the top of an iPhone.

 

Solution Video