To design iPhone or iPad app user interface that resizes for any device you need Auto Layout. Auto Layout enables responsive design between different sizes of iPhones and iPads. In this guide you'll learn 30 Auto Layout Best Practices that you can apply to your own iOS apps. Show
SwiftUI will replace Auto Layout in the future, but if you're still shipping existing apps, you need to understand Auto Layout until SwiftUI is production ready and at feature partity. WWDC 2020 made strides, but SwiftUI is still not enough. Auto Layout is a series of rules that describe the position and size of your images, buttons, and labels in your iPhone app. It allows you to dictate where different images, buttons, labels, and content panels will appear and resize. Rigid pixel-perfect designs are out. Responsive pixel-perfect designs are in. To create captivating mobile experiences your UI designs must scale up and down between the iPhone SE, iPhone 8, iPhone 8 Plus, iPhone X, and iPad. Download the Auto Layout Best PracticesBeginner FriendlyIf you're a beginner and you've struggled with ambiguous layouts, misplaced views, disappearing views, or conflicts then you're in the right spot. Even as an experienced programmer, you may find yourself mystified at why Auto Layout doesn't work like you expect. Auto Layout allows you to define regions to fill a percentage of your iPhone X screen size, to center horizontally, or to maintain equal widths. Feel free to jump around between the different best practices using the table of contents, or the PDF version of the Auto Layout Best Practices. Please let me know what tip is the most helpful. Write a comment below, or send me an email: mailto:[email protected]. If you have any tips, please share them. I can't wait to see what you create! 30 Auto Layout Best PracticesThe 30 Auto Layout Best Practices will give you a head start on working through quirks in Xcode 9 and strategies that will allow you to work faster and more efficiently. Download the guide and you can save yourself from countless hours, days, and even weeks of frustration. 1. Design for iPhone 8Keep it simple. Design your UI for a single iPhone screen first. Auto Layout is a relative and absolute placement tool to create perfect layouts for any iPhone or iPad. Auto Layout gives you control of:
If you watch an artist paint. They don't start painting, instead they start by sketching the forms to prepare the painting. You'll need to do the same thing with your iPhone design. Start with a sketch and plan for one iPhone screen. Next you can start to think about how the design would adapt to new screen sizes. You might ask yourself:
To keep it simple, in Sketch or Illustrator, create a mockup for the iPhone 8 size (W x H: 375 x 667 points). I use Sketch for everything. Exporting images (.png) and vectors (.pdf) is quick and easy (compared to the clunky Illustrator interface). In Sketch you can quickly export @1x, @2x, and @3x images for the different retina resolutions that you can drag-and-drop into Xcode. Workflow: Start Your UI Design
Start my free 4-part iPhone Apps 101 course to learn how to add your images or vectors to Xcode's Asset Catalog. After you have finalized how you'd like the app to look, the next step is to design the UI in Xcode's Storyboard files. 2. Layout Your UI for One iPhoneTranslating a design file into an Xcode Storyboard can take some problem solving skills. To keep it simple, start with the iPhone 8 size. One of the biggest mistakes beginners make is switching between iPhone screen sizes to "check" the layout, only to break things. Save yourself the time and frustration by designing your app UI for iPhone 8 (no one likes to redo work). Here is a Sketch design that has been implemented in Xcode's Storyboard. If you want to learn how to design your first iPhone app, checkout my free 4-part email course (iPhone Apps 101). Your goal is to translate all of the fonts, images, and content from your design mockup into Xcode's Storyboard canvas (watch Lesson 2 from iPhone Apps 101 for details). iPhone SimulatorOn your Mac you can simulator any kind of iOS device, Apple TV, and even Apple Watch. You don't need to own a device to make an iPhone app. ![](https://blog.supereasyapps.com/content/images/2017/11/iPhone-Screen-sizes.jpg full)It's faster to test with a simulator instead of a real device, and smaller iPhone screens will run faster on slower Mac computers. When you open an Xcode project, the default simulator is an iPhone 8 Plus (it's HUGE!). You should always change this to the iPhone 8 Simulator, or you'll end up waiting longer for apps to start. You can test on the different screen sizes after you set your Auto Layout constraints. If you want to run your app on your iPhone using your Apple ID (or using WIFI debugging), watch Lesson 1 from iPhone Apps 101. PreviewXcode has a built in Preview panel that will help you test Auto Layout constraints faster using any iPhone or iPad device. You can test landscape and portrait layouts as you make changes, which will save the hassle of waiting for your app to launch every time you make a change. Workflow: Use Xcode Layout Preview
Storyboard Preview Overview Add New Preview Screens You can test out every combination of screen sizes when you add new screens, or rotate existing. Using preview will be significantly faster than launching each device and manually checking layout changes. Keep in mind, that the preview screen will help you fix problems quickly, but you should test your app on a real device before you submit to the App Store. Test Localization To make sure your layout works in other languages, the "Double-Length Pseudolanguage" will help you determine if you have to fix any layout issues. Languages like German take up almost twice the length of words in English. 3. Undo and RedoYou should never be afraid to make changes. If a button, view, or label moves and you don't like the change: undo and try again. Use the keyboard shortcuts:
You might even add the wrong constraint and see a lot of red. That's a good time to undo and try again. Sometimes I feel dyslexic reading all of the options, and I'll accidentally add the wrong constraint. When this happens I just use undo to get back to a previous step, and then I try again. Tip: For more complex views, like the Stack View, you may have to undo multiple times, instead of just once. 4. Relative and Centered LayoutsLayouts are relative, and to get into that mindset, try and slice up the main content regions of your app. Here's a photo of my dog Row centered in the top third, and three buttons centered along the bottom edge of the photo. Tip: The default spacing between most iOS UI elements is 8 points, and 20 points on the edges. To center content and get more control, you need to add additional subviews (even if these Workflow: Center ContentYour goal is to center a title and subhead using two
5. Identify Structural RegionsAuto Layout constraints are most important when you focus on the areas that will impact the overall structure of an iPhone screen. Identify the big UI elements that lead to the overall structure by thinking about what areas fill the space. ![](https://blog.supereasyapps.com/content/images/2017/11/Brew-coffee-sketch-layout-regions-1.JPG full)Ornamental or supplemental accessory title Workflow: Sketch your UI on paper.
6. Understand the ColorsAuto Layout constraints will not appear to be correct unless they are blue. When you first start adding constraints you are going to see a lot of colors.
Blue: Layout CompleteIf you add all the layout constraints in both the vertical and horizontal directions you will see blue lines and I-beams. When your layout looks blue, that means you have enough layout constraints and that you're finished. Orange: Layout WarningMisplaced Views You might accidentally bump a view, and when that happens after you've already setup the layout constraints is that you'll see orange lines.
Fix it:
Localization Issues New in Xcode 9 are additional warnings about trailing or leading constraints for text labels. These new warnings appear to help developers fix issues with right-to-left language support on iOS 11. You can fix this issue by adding a trailing or leading constraint between the UILabel and the closest neighbor (or edge). Fix it:
OR
Red: Layout ErrorAmbiguous Layout When rules can be interpreted in more than one way, you have an ambiguous layout. This can happen if you have two areas that can both grow vertically. Not being specific on how they should grow creates an ambiguity. To fix the issue:
Layout Conflict Now imagine that both your boss and your direct manager give you instructions for work. One tells you to do X, and the other tells you to do Y. You have a conflict when X and Y are completely different things. Now you need to pick one of them to follow, but doing so will make one or the other upset. Missing Constraints Imagine giving directions to a friend. If you leave one turn out of your directions, they'll get lost. Your directions were not complete. The same is true with Auto Layout, you need to provide complete directions to the iPhone, so that it can position your content in the right spot. Even a simple mistake, or a missing rule can lead to lots of "Missing Constraints". The vertical spacing constraint is missing between the "Calculate Tip" button and the box image around the total. If you look on the hidden Auto Layout panel, it looks like everything is broken. Without this one constraint, none of the layout rules make sense. Adding it back fixes every single error. Broken Rules When you have layout errors, your views, labels, and images will not appear where you expect. The iPhone will have to break one of your rules, or it might not have enough rules to describe the position and size of everything in your UI. 7. Work in One DirectionYou should start top to bottom, and then move left to right. When you haven't defined everything from top to bottom, there are still missing constraints (red), but you shouldn't worry yet. Layout errors (red) are common when you are designing the interface. They should disappear when you finish, otherwise you have a problem. Imagine Auto Layout like directions in a recipe. The dish is not complete until you follow all of the steps. It takes time to do each step, and you won't be able to judge the final result until you finish each step. The same concept applies to Auto Layout:
For beginners the visual feedback can be confusing when you haven't finished adding all the layout rules. The more you practice Auto Layout the easier it is to understand. Stop reading this guide and try it on a test app. Create a new Xcode project and add some images, buttons, and labels. Workflow: Structural Layout
8. The Light at the End of the TunnelUI in progress is going to be hard to tell if it's done, since you need to provide all of the rules in both a vertical and horizontal directions. Keep on adding rules for each of the structural UI elements. Until you finish describing the position and size of your UI elements in a complete area, or subregion you will still see lots of red and blue. Don't worry if you see orange, it just means you may have nudged a view. If you get stuck and it doesn't look right, undo the change and try it again. And if you get really stuck, start over. I do this all the time, don't be afraid to learn from your mistakes by doing it again. The more you practice setting up layout constraints, the more comfortable you will become. Auto Layout errors do not display Fix-Its in the Issues Navigator where Swift code errors appear. You will only see generic errors about ambiguous constraints, but it won't always tell you specifics. Clicking the Warning sign on the top right corner of your Storyboard or .xib interface file will also not show you the exact warning. Depending on the panels you have open, you might not even the hidden layout error panel. Workflow: Show the Hidden Auto Layout Error PanelYou can display detailed errors and warnings about your Storyboard Auto Layout if you show the Auto Layout Error Panel.
Seeing the actual warnings makes it a lot easier to figure out what's missing from your layout constraints. The next background color trick is something I use all the time. 10. Change Background ColorsTo understand how When you test your interface on large or small devices, the fastest way to see if your structure layout constraints are working is to change the background colors from Default (clear or white) to any color. When I change colors for views that are touching (adjacent), I use different colors for each view. That way you can see the edges and verify they are stretching or compressing correctly. When you finish with your layout constraints, and you're satisfied that they behave correctly with the different iPhone simulators, you can revert the colors back to the Default color. Any time something weird happens after I've tweaked a layout, I'll change the background color of the surrounding elements to fix the bug. You can use this same trick for image graphics when you create custom @IBDesignable subviews. One version of the exported images will be "rainbow" colors and the other will be the final color of the app's theme. Working productively with Auto Layout requires optimizing your mouse clicks and interactions. 11. The Diagonal DragThe right-click and drag menu is a quick way for adding Auto Layout constraints. However, the context sensitive menu behavior is not helpful. If you drag left or right you're wasting precious time and doing a lot of extra work. The context sensitive menu tries to only show you the constraints that you might want in a vertical or horizontal direction. However, many times it will hide the actual constraints you need. To get around this quirk (Please report it to Apple), you will need to drag diagonally. Many times the leading or trailing edge constraints are hidden if you just drag horizontally. 12. The Shift Key ModifierWhen you use the context sensitive right-click and drag method of adding Auto Layout constraints, you can save mouse clicks by using the Shift key modifier. After you click and drag, hold down the Shift key as you select multiple constraints to add. Make sure you click the button "Add Constraints" to add the constraints, otherwise you'll need to do it all over again, since they won't add if you click elsewhere on your Storyboard canvas. You cannot add all the layout constraints from the canvas. 13. Adding Difficult ConstraintsYou will need to use the Document Outline on the left of your Storyboard to add constraints using the click and drag method. Adding layout constraints can be tricky with a complex layout.
Workflow: Add Constraints to the Right Views
Tip: You can add constraints between views in the Document Outline layer list. Again, hold shift after dragging to add the leading, top, and trailing constraints in one go. It might seem that your constraints aren't working, when in fact they are. If you work with images the next tip will save you time. 14. Fix the UIImageView Content ModeIf you have a stretchable image, the default behavior of a You will need to change the "Content Mode" on the Not knowing about the Content Mode setting can make your Auto Layout constraints look wrong, and will leave you frustrated. 15. When to Use Stack Views
5's work well in certain situations and are the wrong choice in others. The content in a UIStackView needs to be similar (i.e.: homogenous) or you're going to get strange layouts. The
5 can work great with set of buttons or a custom
7 class or .xib interface file. But if you haven't spent the extra effort to create those "UI widgets", it might be the wrong solution for your UI layout. You can learn how to create a an @IBDesignable class here. From working with many beginner iPhone developers, I believe that you should start with manually laying out all the constraints to understand the behavior or UI elements and Auto Layout. In my experience, a
5 can cause Storyboard performance issues if you have a lot of
5s embedded inside of each other (i.e.: try making a math calculator UI using Stack Views). Part of translating a design into a responsive iPhone app layout requires graphics that can resize without visual artifacts. 16. Design Resizable and Scalable ImagesOn iPhone X or iPhone 8 Plus your images need to fill the extra vertical and horizontal space. A responsive app requires you to think in terms of stretching in either the vertical or horizontal directions (or both). Buttons are typically stretched horizontally in apps, while cover photos might be stretched both vertically and horizontally to fill the space. If you have a custom graphic for a callout widget, you might want to maintain an aspect ratio, yet support growing or shrinking the graphic (and related labels) based on the screen width or height. Resizable graphics are easy if the design graphic is a solid color. Resizing a button graphic with a gradient limits you to a horizontal direction, or you'll see the stretch skew your gradient colors and your rectangle's corner radius. Resizing a button graphic that isn't designed to stretch with cause discoloration and graphics artifacts, which makes your UI look strange (Visual artifacts distract from the user experience). 17. Stretch Correctly with Image SlicingXcode has built in support for slicing images to make them resizable. After you import an image into the Assets Catalog (Assets.xcassets) click on the image/vector on the left sidebar, there is an option hidden in the bottom right corner of the canvas to "Show Slicing." Enable Slicing with the Asset Catalog
Keep in mind how your graphic is designed in order to make it stretch. The above "Tip Callout" image will only look good stretched vertical. If you stretch the "Tip Callout" image horizontally the bottom arrow will be off to a side, or skewed. Decoding Slicing Regions Xcode slicing will enable you to specify end caps (vertical and/or horizontal), a stretchable region, and an exclusion region.
The width of your graphic will determine how wide the button's intrinsic (or default) size appears on the screen (Storyboard canvas). Stretchable graphics can always get bigger, but they cannot get smaller than their intrinsic size without visual artifacts. 18. Create Custom @IBDesignable UIViewsUsing the strategies above for creating a complex stretching effect you'll need to create an
7 element if you want to layout the interface with Storyboard.
19. Advanced Image ResizingTo achieve some visual affects you will need to break apart a design element into multiple images. When you look at a graphic, there may be embellishments or frills that need to stay in specific positions. For example, with this tip calculator callout, you want the bottom arrow to stay centered. If the graphic resized using one of the sides, the arrow would be aligned on the a side, and it won't align to the label that is centered below the graphic. You have a visual disconnect that is very distracting for the user, and that doesn't match your design. Break Down Design Elements Into Resizable PartsTo achieve some visual effects you need to separate a design element into it's components that can be stretched with Auto Layout constraints either in Storyboard files or programmatically. For this effect you'll need at least three images/vectors, depending on how you slice apart and build the UI element. Compare the colored borders to the final composition to see how the graphics fit together.
Important: These vectors are exported from separate Artboards in Sketch so that the vertical offsets align (Notice the white space below the vectors). Some elements will be static sizes like the arrow and the left and right edges of the rounded rectangle. If you were to stretch these elements it will distort the arrow or the corner radius. Reference the colored composition above to the parts. In the horizontal direction, I only want to stretch a portion of the horizontal bar that's on both the left and right sides of the arrow. The stretch region will need to stretch equally on both sides, or the arrow will be off center. Since I'm using a rounded rectangle, the flat middle portion will also need to stretch in the center of the graphic. Xcode's slicing will make this work with minimal effort. In Xcode you can create an
7 UI element with the horizontal UIImageViews using some vibrant colors to show regions. @IBDesignable .xib FilesIn Xcode you can create a programmatic
7 `UIView`3 file, or you can do the same thing using an `UIView`4 interface file. Tip 1: Show the bounds of each image when working with your Storyboard or .xib file: `UIView`5 Tip 2: You can create multiple copies of your view to use the vibrant debug colors. These are good places to practice Auto Layout. Final Custom IBDesignable Effect in StoryboardUsing an IBDesignable view makes a design customizable UI element that you can drag around your Storyboard file. It is adaptive and can stretch or shrink to different device sizes with the proper Auto Layout constraints. After the auto layout constraints are added, you can swap out the colored variations of the view with the white and gray style with a corner radius of 4. Layer Breakdown
20. Resizable UIImages using Swift 4 CodeYou can achieve the same effects from slicing in Xcode using the `UIView`6's `UIView`7 method in Swift.
The following Swift 4 code will display a white rectangle vector with a corner radius of 4. Using a edge inset of 5 on all sides enables the graphic to resize without any distortions with the 4 point corner radius.
Tip: Changing the `UIView`8 to `UIView`9 enables you to create patterns that resize to fill an area. Xcode Asset Catalog Effect Breakdown
Links
21. Advanced Constraints EditorWhen you use the right-click and drag method to add constraints (or the align and pin buttons) Xcode will sometimes add the wrong constraint. You can edit the details of any constraints using the constraint options on the "Measurement" panel on the right side. Let me know if you want to learn more about editing constraints in an upcoming tutorial: mailto:[email protected] 22. Test Different iPhone Size ClassesAfter you add all your constraints for iPhone 8, you can now test what the constraints will do on different iPhone sizes. Important: Only do this step after you add all the constraints for both the vertical and horizontal positions. You may need to do a bit of problem solving to fix layout issues at this stage, since your layout should work perfectly for the iPhone 8 (if it doesn't fix those issues first). Generally I will test between the iPhone 8 and iPhone 8 Plus size first. Then I test for iPhone X. And lastly, I test for iPhone SE. 23. Fix Constraint ConflictsMaking changes later on is inevitable. Adding a new view, or changing the distance between margins will cause your layout to break. Typically the view will not disappear in the Assistant Editor Preview, but it will disappear when you run on a real device or simulator (along with any views that might be touching it). InequalitiesThere are situations where you may need to make a view height or width `UILabel`1 (greater than or equal to) or `UILabel`2 (less than or equal to) a size.
Workflow: Testing Your Layout Constraints on Different Size ClassesYou can switch between different size classes (and devices) using the buttons on the bottom bar of your Storyboard file.
Updating Previous ConstraintsAfter setting all the heights, you might need to add a new
24. The One ViewAs a rule of thumb, you can have one view that doesn't specify a rigid width or height in your overall vertical and horizontal structure. This view can pick up any of the slack that you may need to properly space out elements. More than two views without solid heights will cause ambiguous layout problems. If you have more than two that need to grow and shrink, then you'll need to add additional constraints to describe how they should behave.
To do more complex layouts either you will need to use a Stack View to help describe spacing, or you will need to add hidden UIView's that can have equal width or height constraints. 25. Frames vs. Constraint ConstantsWhen you see dashed orange lines the Storyboard canvas layout will not match the UI layout when you run your app on your device or iPhone Simulator. You have two options:
Update FramesFrames in the context of Storyboard files with Auto Layout are the canvas positions of the UI that you have dragged onto the main view. The frame describes both the origin (x and y position) and the size (width and height) in terms of points on the screen. When you add a layout constraint, or when you nudge a view around the Storyboard canvas, it may change some of your view's frame values. But this change will not propagate into Auto Layout rules.
Workflow: Make an Auto Layout Change (Update Constraint Constants)When you want to move a view, you will need to update any Auto Layout constraints that have been previously set.
Workflow: Revert a Layout Change (Update Frames)As you click around your Storyboard file, you may miss-click. If that happens and you accidentally move a view, you can move it back using a quick button press.
26. Iterate Quickly with CopiesYou can always duplicate a complex UIViewController and then apply changes, and see if you can get things working.
27. Backup Auto LayoutYou should be backing up your work with version control. Git is the best, since it is built into Xcode and your Mac. Git enables you to track changes like you might do in Word when writing a paper with a group. You can see who made a change, and when. Sometimes you might not even remember making the change. You can go back in history before you broke a feature, which is why version control is so useful for apps. Use one of these two strategies with your iPhone apps: Workflow: Easy Backup Strategy
Workflow: Git Version ControlUse Git locally with your project and make commits as you work. I use <Github.com> for all my source code. I don't feel comfortable not having it backed up to the cloud in either a public or a private repository. Check out my public code: http://github.com/PaulSolt
At the very least you now have a way to "go back in time" if you break something. If you connect your local git repository to your own GitHub account, you'll be able to protect against losing code if your hard-drive crashes or if someone steals your laptop. 28. Clear Constraints and RestartIf you get stuck, just start over.
29. Alignment and Tie Fighter ButtonsThe bottom right corner contains three buttons that are very useful in quickly adding new constraints to multiple views. Align ButtonYou can align multiple views together, or to a superview (the containing view). Make sure you select multiple views before you click the align button. Square Tie Fighter Button (Add New Constraints)You can add multiple constraints in less clicks using the "Add New Constraints" button. After you understand how constraints work, this button can save you time. Triangle Tie Fighter Button (Resolve Auto Layout Issues)Use this button to clear constraints or to update constraint constant values. 30. Don't Use These SettingsAvoid the options to "Reset to Suggested Constraints" and "Add Missing Constraints". It might seem like a quick fix, but it rarely ever adds the constraints you really want. Xcode can't automatically create rules if you don't know what you want the UI to do. In a pinch, it might help you diagnose a problem, but most likely it will just pin the element incorrectly. The few times I use the "Reset to Suggested Constraints" button I immediately undo what Xcode adds and do it again myself. My other problem with this "magic" button it is that you have no idea what changes unless you painstakingly undo and redo. You should be able to reason about all the rules in your interface, it shouldn't be magical. Understanding layout and where things need to get pinned, and the relationship between your user interface elements is something that you need to figure out. Download the 30 Auto Layout Best Practices PDFDownload the Auto Layout Toolkit and get the Auto Layout 101 video and the 30 Auto Layout Best Practices PDF. Please let me know what tip is the most helpful. Write a comment below, or send me an email: mailto:[email protected]. If you have any tips, please share them. I can't wait to see what you create! Thank You!Let me know if you learned anything from the 30 Auto Layout Best Practices. Send me an email to mailto:[email protected] What is the keyboard layout guide?Apple says A layout guide that tracks the keyboard's position in your app's layout. In simple words KeyboardLayoutGuide help us to setup view frame according to the keyboard position when keyboard appears in the screen. What is auto layout in Swift?Auto Layout is a way that lets developers create a user interface by defining relationships between elements. It provides a flexible and powerful system that describes how views and UI controls relate to each other. How do you add constraints to a storyboard?Adding ConstraintsOpen the Attributes Inspector: In the right-hand panel, open the Attributes Inspector (the icon looks like a slider control). Click on the "+” Button: Under the "Constraints" section of the Attributes Inspector, click on the "+" button. This will open a dropdown menu with various constraint options. How to set constraints in Swift?The goal of this article is to explain how you can add constraints programmatically in the Swift language. To programmatically add constraints in Swift, you can use the NSLayoutConstraint class to define the constraints you want to add. |