UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to fix Auto Layout problems

Swift version: 5.6

Paul Hudson    @twostraws   

If your Auto Layout code isn’t behaving the way you want, there’s a good chance you’re seeing Xcode spew errors into its log while your user interface is thoroughly broken. There are a few steps you can take that might help, and I want to walk through each of them here.

First, customize the identifier property of each of your constraints. This is a free-text string that can be whatever you want, so use it to give your identifiers meaningful name “Image View aligns its right edge to the title label” for example. When Xcode spits out Auto Layout errors in the future, this identifier will be included so you get a better idea of what’s causing the problem.

Second, try calling the exerciseAmbiguityInLayout() method of the view that’s causing problems. This is a method specifically designed to debugging, and causes a view to randomly shift between all layouts that are possible given the constraints you’ve applied. If you run this a few times then it should be clear what’s causing the issue: if two views vary in their widths, it means your current constraints don’t make it clear which is the correct layout.

Third, try creating your constraints in Interface Builder. You don’t need to keep them there if you prefer doing things in code, but if you try to create them in IB you’ll be able to see visually where the problem is – IB will flag up a warning or error depending on your mistake.

Finally, try pasting Xcode’s Auto Layout errors into http://www.wtfautolayout.com/. This is a web service that reads Xcode Auto Layout errors and converts them into a graphical representation of what’s happened. It won’t direct you to the solution, but it might at least help make it clearer.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 9.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.