How to add constraints programmatically using Swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Programmatic Auto Layout is the right tool when views are created dynamically, reused across screens, or difficult to express cleanly in Interface Builder. The main idea is simple: create the view, disable autoresizing-mask translation, add it to the hierarchy, and then activate a small set of constraints that clearly describe the layout contract.
Start With Anchors and translatesAutoresizingMaskIntoConstraints
The most important setup line is usually this one:
If you forget it, UIKit creates constraints from the view's autoresizing mask and those often conflict with the constraints you add manually.
After that, use anchor-based constraints as the default style:
Anchor APIs are easier to read than older factory-style NSLayoutConstraint initializers, and they give compile-time help by separating horizontal, vertical, and dimension anchors.
Use Safe Areas and Meaningful Containers
A common early mistake is pinning everything to the raw edges of the root view. On modern devices, safe areas usually describe the visible and usable content region much better.
As layouts grow, it is usually cleaner to constrain groups of views inside container views or stack views than to create a dense web of cross-screen constraints.
Prefer Flexible Layouts Over Hardcoded Sizes
Fixed heights are easy to write and easy to regret. Text size, localization, and device size changes all punish rigid layouts.
When possible, let labels and controls use intrinsic content size. For views that need bounds, use minimums, maximums, or priorities instead of only hard constants.
This gives Auto Layout room to adapt instead of forcing impossible layouts when space is tight.
Store Only the Constraints You Need to Change
Most constraints can stay inside one activation block and never be referenced again. Keep a property only for constraints that will change later, such as keyboard adjustments, expansion panels, or animated position changes.
Notice that the animation updates an existing constraint. It does not create a new conflicting one.
Debug Constraint Problems Methodically
When Auto Layout breaks, do not guess. Check these in order:
- Was
translatesAutoresizingMaskIntoConstraintsdisabled - Is the view already in the hierarchy before constraining it
- Are there enough constraints to determine size and position
- Are there conflicting fixed sizes with no flexible alternative
- Do the console logs name one unsatisfiable constraint chain
Constraint bugs get easier when layout code lives in a dedicated setup method called once. Recreating constraints in viewDidLayoutSubviews or scattering them across unrelated callbacks makes conflicts harder to reason about.
Common Pitfalls
The most common mistake is forgetting to set translatesAutoresizingMaskIntoConstraints = false before adding manual constraints.
Another frequent issue is over-constraining a view with too many fixed constants. Developers also often pin to raw screen edges when they should use safe areas, or they create new constraints every time the UI changes instead of updating the constants on existing ones.
Summary
- Disable autoresizing-mask translation on views you constrain manually.
- Use anchor-based constraints as the default Auto Layout style in Swift.
- Prefer safe areas and container-based layout structure over raw edge pinning.
- Use priorities and flexible dimensions instead of hardcoding every size.
- Keep references only to constraints you plan to update later.
Related reading
- How to add dividers and spaces between items in RecyclerView
- How to add dividers and spaces between items in RecyclerView
- How to add Done button to Numpad in iOS using Swift?
- How to add HeaderView in UICollectionView like UITableView's tableHeaderView
- How to add leading padding to view added inside an UIStackView
- How to add leading padding to view added inside an UIStackView
- How to add 'libs' folder in Android Studio?
- How to add line break for UILabel?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.