How to use NSLayoutConstraint programmatically in Swift
UIKit can position views by calculating relationships rather than storing fixed frames. With Auto Layout, a width might be linked to a readable range, a label might sit below another label, and a button might remain attached to the safe area. These relationships become NSLayoutConstraint objects that UIKit solves whenever the layout changes.
This guide uses Swift and UIKit without a storyboard. The process is straightforward: build a view hierarchy, turn off automatic frame translation for manually managed views, create constraints with layout anchors, and activate them. Although anchor syntax looks different from constructing NSLayoutConstraint directly, each anchor method returns an NSLayoutConstraint instance.
For apps entering the Australian market, test data should include Australian English spellings such as “colour”, “favourite” and “centre”, long place names from Sydney to Townsville, AFL club names and scores, and directions suited to left-hand traffic. These details expose weak layouts faster than a perfectly centred placeholder, especially when Dynamic Type and different iPhone widths are involved.
Why programmatic Auto Layout earns its place
Frame-based layouts are useful for some custom drawing, but they become brittle when content, orientation or available space changes. Programmatic Auto Layout stores intent: “keep this caption below its title” or “let these two columns share the remaining width”. UIKit then calculates coordinates for the current screen, which is safer than repeatedly recalculating frames for every device size.
Building constraints in Swift also makes layout logic reusable. A card view can be created in a feed, placed in a detail screen or previewed in a test, while the same constraints continue to describe its internal structure. Code review can catch broken relationships, and unit tests can verify constants and priorities without opening Interface Builder.
The approach is especially valuable for junior developers because it makes layout decisions visible in source control. Names such as titleTop or cardTrailing reveal purpose, while a constraint equation can be examined precisely. The goal is not to avoid Interface Builder; it is to choose a layout method that fits the product and the team.
Preparing views and choosing anchors
Start with the hierarchy, not the equations. A view can only participate in a relationship with another view when both are in the same hierarchy, and views connected by constraints must share a common ancestor. Add each subview before creating its constraints, then set translatesAutoresizingMaskIntoConstraints to false for every view whose position and size you will manage yourself.
let container = UIView()
let card = UIView()
let titleLabel = UILabel()
let subtitleLabel = UILabel()
container.addSubview(card)
card.addSubview(titleLabel)
card.addSubview(subtitleLabel)
card.translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
Layout anchors offer type-safe connections: topAnchor, bottomAnchor, leadingAnchor, trailingAnchor, centerXAnchor, centerYAnchor, widthAnchor and heightAnchor. Attach content to safeAreaLayoutGuide when it should avoid the notch, home indicator or rounded screen corners. For a readable view, leading and trailing constraints can stop text from touching the display edge.
Constraint code still lives inside a configured project, so the deployment target, SDK and interface settings remain important even when every view is created in Swift. That separation between tool configuration and application behaviour also appears in NetBeans Jakarta EE setup, where environment settings shape what a Java application can run. In UIKit, confirming the target and hierarchy prevents a similar class of surprise.
Building and activating constraints
Anchor methods return constraints that remain inactive until they are attached to a view or activated as a group. Creating a strong reference is rarely necessary; activation is what registers the rule with UIKit’s layout engine.
Once the card has been positioned within its container, its internal relationships can be defined like this:
let titleTop = titleLabel.topAnchor.constraint(
equalTo: card.topAnchor,
constant: 16
)
let titleLeading = titleLabel.leadingAnchor.constraint(
equalTo: card.leadingAnchor,
constant: 16
)
let titleTrailing = titleLabel.trailingAnchor.constraint(
equalTo: card.trailingAnchor,
constant: -16
)
let subtitleTop = subtitleLabel.topAnchor.constraint(
equalTo: titleLabel.bottomAnchor,
constant: 8
)
let subtitleLeading = subtitleLabel.leadingAnchor.constraint(
equalTo: card.leadingAnchor,
constant: 16
)
let subtitleTrailing = subtitleLabel.trailingAnchor.constraint(
equalTo: card.trailingAnchor,
constant: -16
)
let cardBottom = card.bottomAnchor.constraint(
equalTo: subtitleLabel.bottomAnchor,
constant: 16
)
NSLayoutConstraint.activate([
titleTop, titleLeading, titleTrailing,
subtitleTop, subtitleLeading, subtitleTrailing,
cardBottom
])
constant describes the fixed gap in a relationship, while a multiplier scales one side of the equation. A trailing constraint normally uses a negative constant, such as -16, because the label’s trailing edge sits 16 points before its container’s trailing edge. Prefer inequalities such as greaterThanOrEqualTo when a minimum size matters more than an exact size.
UIStackView is a useful companion rather than a replacement for Auto Layout. Give it arranged subviews, set its axis and spacing, disable frame translation on the stack, and constrain the stack to its container. The stack then manages spacing and distribution among its children. Avoid adding separate constraints that dictate the same children’s positions, or the two systems will compete.
Priorities, intrinsic size, and resilient layouts
Constraint priorities decide which rule UIKit should break when preferences conflict. A priority of 1000 is required; lower values can be adjusted. Content hugging resists making a view larger than its intrinsic content size, while compression resistance resists making it smaller. UIKit commonly starts horizontal hugging at 250 and compression resistance at 750, though the right choice depends on the component.
Insufficient equations create ambiguity, even when every constraint has the same priority. If two labels have equal width and height, yet neither is tied to another dimension, UIKit may report an ambiguous layout. Before changing a priority, inspect the equations and ask whether the hierarchy supplies enough information to determine every view’s size and position.
UILabel and UIButton provide useful intrinsic content sizes, so text can determine their dimensions. A custom view usually does not unless it overrides intrinsicContentSize. If custom content changes at runtime, update the relevant properties and call invalidateIntrinsicContentSize. Otherwise Auto Layout may continue using a stale measurement even though the screen appears to contain new content.
Resist fixed width and height constraints for text. A label carrying “Melbourne” should be allowed to use the space it needs, while a caption with several lines should grow vertically. Use leading and trailing constraints, sensible compression priorities and stack views for variable groups. Test long strings, accessibility text sizes, portrait and landscape, including the compact widths found on current iPhones.
A practical checklist before you debug
A short review catches common Auto Layout mistakes before the debugger becomes a maze of temporary constraints. Keep the first checklist focused on setup and the second on runtime evidence.
View and constraint setup
- Confirm every constrained view has a place in the intended hierarchy.
- Disable autoresizing translation only on views managed by explicit constraints.
- Connect edge content to the safe area and scrollable content to the scroll view.
- Give important constraints clear names when several rules describe one view.
Runtime checks
- Inspect ambiguous-layout and unsatisfiable-constraint messages in the console.
- Print
constraintsAffectingView(for:)for the relevant layout axis. - Use Xcode’s View Debugger to inspect frames and spacing on each screen.
- Retest after changing priorities, intrinsic sizes or displayed content.
When a constraint is unsatisfiable, the console often names two rules that cannot both be true. Temporarily deactivate one, locate the conflicting constraint and restore a valid relationship rather than lowering every priority. setNeedsLayout() followed by layoutIfNeeded() can force an update while you inspect the result. Ambiguity means more than one layout can satisfy the rules, not necessarily that the screen looks wrong, which is why a quick visual check is not enough.
The constraint mindset for reliable layouts
Programmatic Auto Layout is a small algebra of relationships. The hierarchy supplies the objects, anchors express the links, constants and priorities tune the result, and UIKit performs the calculation. NSLayoutConstraint is the rule at the centre of that process, whether it was created through an anchor or an explicit initialiser.
Reliable interfaces come from unambiguous intent. A clean hierarchy has one common ancestor for related content; edge, centre and dimension constraints have distinct jobs; and variable text is allowed to affect the layout. Those habits scale from a single card to a complete app for the Australian market.
The lesson to remember is that every constraint should express one clear relationship, every view should have a sensible place in the hierarchy, and every layout should be tested with real content rather than an idealised screen.