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.
Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!
Available from iOS 9.0
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Need to know Objective-C fast?
I wrote a book dedicated to teaching Objective-C to developers who already know Swift – it's the fastest way to get up to speed!