Fix: Subview Not Respecting Aspect Fit with AutoLayout Constraints in Xcode

Written by

in

Quick answer: Add five constraints to the subview: a required aspect-ratio constraint, required width ≤ container width, high-priority width = container width, required height ≤ container height, and high-priority height = container height. Then center the subview horizontally and vertically. If the subview fills the container instead of fitting, the ≤ constraints are reversed—swap the first and second items in each constraint.

Why this happens

AutoLayout resolves ambiguity by satisfying required constraints first, then minimizing error on lower-priority constraints. To mimic UIViewContentModeScaleAspectFit, the subview must grow until it hits one container edge while staying inside both. A single equality constraint on width or height would force the subview to match that dimension exactly, which produces aspect-fill behavior when the container’s aspect ratio differs from the subview’s.

The solution uses pairs of constraints on each axis: a required less-than-or-equal constraint that caps the subview at the container’s size, plus a high-priority (750) equality constraint that pulls the subview toward that cap. Because the aspect-ratio constraint is also required, AutoLayout can only maximize the subview along one axis—the one that hits its cap first—exactly like aspect-fit.

A common pitfall: when you create an equal-width constraint in Interface Builder, Xcode may set the first item as the container and the second item as the subview. Changing the relation to “Less Than or Equal” then reads “container.width ≤ subview.width,” which is the opposite of what you need. The subview then expands to the container’s full size (aspect-fill) instead of stopping at the first edge (aspect-fit).

How to fix it

1. Set up the five core constraints in Interface Builder (Xcode 5.1+)

  1. Select the subview in the storyboard or xib.
  2. Aspect ratio: Control-drag from the subview to itself, choose Aspect Ratio. This creates a required (priority 1000) constraint locking the subview’s intrinsic ratio.
  3. Width ≤ container: Control-drag from the subview to its container, choose Equal Widths. In the Size inspector, change Relation to Less Than or Equal. Verify the constraint reads “Subview.width ≤ Container.width” (first item = subview). Keep priority Required (1000).
  4. Width = container (high priority): Create another Equal Widths constraint to the same container. Leave Relation as Equal, but set Priority to High (750). Again confirm “Subview.width = Container.width”.
  5. Height ≤ container: Repeat steps 3–4 for Equal Heights with Less Than or Equal and Required priority.
  6. Height = container (high priority): Repeat for Equal Heights with Equal relation and High (750) priority.

2. Center the subview

Add two required constraints:
– Center Horizontally in Container
– Center Vertically in Container

These keep the subview centered regardless of which dimension hits its cap first.

3. Verify constraint direction (critical)

Select each ≤ constraint in the Document Outline. In the Size inspector, check First Item and Second Item.
– For width: First Item must be the subview, Second Item the container.
– For height: same.

If reversed, click the constraint’s Edit button (or double-click the constraint in the canvas) and swap the items using the dropdown arrows. The constraint should read “Subview.width ≤ Container.width” not “Container.width ≤ Subview.width”.

4. Programmatic alternative (Swift)

If you prefer code, create the constraints in viewDidLoad or updateConstraints():

import UIKit

class AspectFitContainerView: UIView {
    let childView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    private func setup() {
        childView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(childView)

        // Example intrinsic aspect ratio 4:3
        let aspectRatio = childView.widthAnchor.constraint(equalTo: childView.heightAnchor, multiplier: 4.0 / 3.0)
        aspectRatio.priority = .required

        let widthLE = childView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor)
        widthLE.priority = .required

        let widthEq = childView.widthAnchor.constraint(equalTo: widthAnchor)
        widthEq.priority = UILayoutPriority(750)

        let heightLE = childView.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor)
        heightLE.priority = .required

        let heightEq = childView.heightAnchor.constraint(equalTo: heightAnchor)
        heightEq.priority = UILayoutPriority(750)

        let centerX = childView.centerXAnchor.constraint(equalTo: centerXAnchor)
        let centerY = childView.centerYAnchor.constraint(equalTo: centerYAnchor)

        NSLayoutConstraint.activate([
            aspectRatio,
            widthLE, widthEq,
            heightLE, heightEq,
            centerX, centerY
        ])
    }
}

5. Quick test

  1. Give the container a background color so you can see its bounds.
  2. Give the subview a contrasting color.
  3. Run on different device sizes (iPhone SE, iPhone 16 Pro, iPad).
  4. Rotate the device. The subview should always stay inside the container, centered, and never exceed the container’s width or height.

How to prevent it

  • Always verify constraint direction after changing a constraint’s relation to ≤ or ≥ in Interface Builder.
  • Use named priorities (.required, .defaultHigh, UILayoutPriority(750)) instead of raw numbers for readability.
  • Test on multiple aspect ratios (compact width, regular width, landscape) before shipping.
  • Avoid mixing this technique with contentMode = .scaleAspectFit on a UIImageView—pick one approach.
  • Document the constraint set in a comment or README; the five-constraint pattern is non-obvious to newcomers.

FAQ

Why does my subview still fill the entire container (aspect-fill) instead of fitting?

The ≤ constraints are reversed. Open each constraint in the Size inspector and ensure the First Item is the subview and the Second Item is the container. If they’re swapped, the constraint reads “Container ≤ Subview,” which forces the subview to be at least as large as the container.

Can I use this with a UIImageView that already has an intrinsic aspect ratio?

Yes. If the UIImageView has an image set, its intrinsic content size provides the aspect ratio automatically. You can skip the explicit aspect-ratio constraint and keep the four width/height constraints plus centering.

What priority should the equality constraints use?

750 (High) works well. It must be lower than Required (1000) so the ≤ constraints win when they conflict, but high enough that AutoLayout prefers the equality when both can be satisfied. Avoid 900 or 1000—that would make them required and cause unsatisfiable constraints when the container’s aspect ratio differs from the subview’s.

Does this work with stack views or safe-area layout guides?

Yes. Constrain the container to the stack view or safe area as usual. The aspect-fit logic lives entirely between the container and its immediate subview, so the container’s own layout source doesn’t matter.

Can I animate changes to the container’s size?

Absolutely. Since all constraints are standard AutoLayout constraints, animating the container’s frame or its own constraints (inside a UIView.animate block with layoutIfNeeded()) will smoothly animate the subview’s aspect-fit resize.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.