For some reason getting a grasp on ios auto layout programmatically seemed to be a bit of a challenge and most of the resources I found on it were scattered or not very good.
The official Apple docs on ios auto layout programmatically seemed over the top on theory and then how it describes what you should do isn’t very clear, at least for me anyways.
I found the following to be pretty helpful in understanding it clearly and a good approach:
- Watch this video. The guy explains in the first seven minutes what exactly Auto Layout is looking for in order to work: https://www.youtube.com/watch?v=R0PrgE_PKSg
- Learn about anchors:
- Bookmark these resources from Apple:
- You may not need it right away but understand what the compression resistance and hugging priorities are.
- The default content compression resistance priority is 750.
- The default content hugging priority is 250.
- Don’t forget to set
translatesAutoresizingMaskIntoConstraints = false.
- The constraints won’t always show until you call <myView>.layoutIfNeeded().
- Activate and Deactivate constraints. Don’t use add/remove.
- Keep a reference to the constraints that you will change later.
- Wrap a UIView.animate around the constraint changes and layoutIfNeeded() call.
- Create some basic layouts with Xcode and see how things do and don’t work – keep it simple and then build on that. Some suggestions of things to make:
- A background image/color expanding the entire width and height of the screen.
- An image centered in the middle of the screen, offset from the top.
- A dropdown accordion. Example: https://codepen.io/fainder/pen/AydHJ
- Two buttons, side by side equal spaced and equal size. Hint: https://stackoverflow.com/questions/28148843/ios-autolayout-two-buttons-of-equal-width-side-by-side
- A scroll view with a content view inside of it with components in the content view to make the content view be a dynamic height.
- Add items that change location on the screen from tapping, and animate with UIView.animate. Take it a step further and do with Keyframe Animation.
- Go watch the 2015 WWDC Videos on Mysteries of Auto Layout. Note: Must use Safari to view.
Follow all of the items under the resource guide and you will be a lot more confident with doing ios auto layout programmatically.