iOS 9 made coding Auto Layout constraints far easier! Learn everything you need to know about layout guides and layout anchors in this Auto Layout tutorial.
Don’t active the constraints like that. Push all the constraints into an array, and then pass the array to the activateConstraints status method on NSLayoutConstraint. See the note on the docs for that method > Typically, using this method is more efficient than activating each constraint individually.
Hi, gargoyle - if you keep reading, you’ll find a section called Activating Arrays of Constraints:
Setting each individual constraint’s active property as you have been doing so far is not as efficient as setting up all the constraints first and activating them all at once.
But thank you for emphasising this important point. My intention was to get people up and running with the simplest code and then optimise it.
Sorry Lots to this tutorial. I got sidetracked early.
Looking at your great chart on the constraint cycle. Am I reading your chart properly such that if I were to call setNeedsUpdateConstraints() then setNeedsLayout() and setNeedsDisplay() are automatically called for me?
You can easily find out what’s called when, by putting in print statements and adding the methods you’re interested in. For example, in AvatarView you could change updateConstraints and layoutSubviews to print out what’s happening:
The way I understand it, and if you want to see the complete cycle in depth, I’d recommend watching Apple’s Mysteries of Auto Layout Part 2 Mysteries of Auto Layout, Part 2 - WWDC15 - Videos - Apple Developer, is that those methods will only be called if they need to be called.
So if you add those print statements, you will be able to see that when you swipe from page 1 to page 2, both updateConstraints and layoutSubviews are called, but not drawRect. But if you go back to page 1, and swipe as if you are going to a previous page, nothing changes in the auto layout engine, so only updateConstraints is called (due to setting the image in ViewController’s updateViews() in ViewControllerExtension.swift. layoutSubviews isn’t called. And drawRect isn’t called at all because it doesn’t need to be.
Very informative and useful tutorial. I usually hate writing constraints in code because of the methods are long and you have to write tons of them and it all ends of an unreadable mess. Using layout anchors seems way cleaner and easier to understand.
Great tutorial, Caroline, it really puts everything in place, thanks a lot!
Do you plan on updating it for iOS 11, in which the view controller’s top and bottom layout guides were deprecated and the view’s safe area layout guide appeared?
This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]