Stop Using Dummy UIViews as NSLayoutConstraint Boundaries

If you’ve ever used Auto Layout, you’ve likely run across the need to add some “dummy” UIViews to the main view to provide boundaries for the constraints of other UIViews. This allows the spacing between these child views to remain the same, while their positions on the screen can change.

Dummy
Stop using dummies, period.

Perhaps you need a login screen. You need UILabels that say “Email” and “Password” that are lined up with their corresponding UITextFields. Of course, the UILabels and UITextFields will also need their right edges aligned. The space between the UILabels and UITextField needs to stay the same, and they also need to be horizontally and vertically centered with the main UIView.

Before iOS 9 you would simply parent the UILabel and UITextField within some other UIView. You could then set that “dummy” UIView to have a certain height and width and to be horizontally and vertically centered within the main view. Then you can set constraints on the UILabels and UITextFields to their superview’s edges and you’re golden.

I did exactly that in Interface Builder:

Screen Shot 2015-07-23 at 2.46.11 PM

The problem is that UIView classes are expensive. In this case your dummy view isn’t doing anything itself, other than acting as a boundary for the constraints of its child views.

That’s why in iOS 9 Apple added UILayoutGuides which are ways to specify rectangular bounds on the screen. Your actual UIViews can then have their constraints anchored to these UILayoutGuides.

UILayoutGuides are not UIViews and they take up less memory. Use them to avoid unnecessary UIView nesting and to help keep your app light and responsive. Adding “dummy” UIViews to your view hierarchy means that iOS had to send messages through that view when they traverse up or down the UIView tree.

UILayoutGuides have no support in Interface Builder (as of iOS 9 Beta 3). They must be added programatically via the addLayoutGuide function on UIView.

One thought on “Stop Using Dummy UIViews as NSLayoutConstraint Boundaries

Comments are closed.