iOS
aspect ratio
auto layout
programming
constraints

How can I set aspect ratio constraints programmatically in iOS?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

An aspect ratio constraint tells Auto Layout to keep a view’s width and height in a fixed proportion. This is the right tool when an image view, video container, or custom control should stay square, stay 16:9, or preserve any other stable shape across device sizes.

The Core Idea

Unlike constraints that pin a view to another view, an aspect ratio constraint usually relates a view to itself. In practical terms, you tell Auto Layout that one dimension is a multiplier of the other dimension.

For a square view, width equals height.

For a 16:9 rectangle, height equals width multiplied by 9.0 / 16.0.

Once that ratio exists, other constraints can determine the actual size and position.

Example: A Square Thumbnail View

The anchor-based API is the easiest way to create the constraint programmatically.

swift
1import UIKit
2
3final class ThumbnailViewController: UIViewController {
4    private let thumbnail = UIView()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        view.backgroundColor = .systemBackground
9
10        thumbnail.backgroundColor = .systemBlue
11        thumbnail.translatesAutoresizingMaskIntoConstraints = false
12        view.addSubview(thumbnail)
13
14        NSLayoutConstraint.activate([
15            thumbnail.centerXAnchor.constraint(equalTo: view.centerXAnchor),
16            thumbnail.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
17            thumbnail.widthAnchor.constraint(equalToConstant: 120),
18            thumbnail.heightAnchor.constraint(equalTo: thumbnail.widthAnchor)
19        ])
20    }
21}

The last line is the aspect ratio constraint. Because height is constrained equal to width, the view stays square.

Example: A 16:9 Image View

For non-square ratios, use the multiplier form.

swift
1import UIKit
2
3final class PlayerViewController: UIViewController {
4    private let posterImageView = UIImageView()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        view.backgroundColor = .systemBackground
9
10        posterImageView.backgroundColor = .secondarySystemBackground
11        posterImageView.contentMode = .scaleAspectFill
12        posterImageView.clipsToBounds = true
13        posterImageView.translatesAutoresizingMaskIntoConstraints = false
14        view.addSubview(posterImageView)
15
16        NSLayoutConstraint.activate([
17            posterImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
18            posterImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
19            posterImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
20            posterImageView.heightAnchor.constraint(equalTo: posterImageView.widthAnchor, multiplier: 9.0 / 16.0)
21        ])
22    }
23}

This keeps the image view at 16:9 while allowing the screen width to determine the final size.

The Older NSLayoutConstraint Initializer

You may still encounter the lower-level initializer in older codebases.

swift
1let ratioConstraint = NSLayoutConstraint(
2    item: posterImageView,
3    attribute: .height,
4    relatedBy: .equal,
5    toItem: posterImageView,
6    attribute: .width,
7    multiplier: 9.0 / 16.0,
8    constant: 0
9)
10posterImageView.addConstraint(ratioConstraint)

This works, but the anchor-based version is shorter and easier to read.

How Aspect Ratio Works with Other Constraints

An aspect ratio constraint does not fully size a view by itself. It only defines the relationship between width and height. You still need enough additional constraints to determine at least one dimension and the position.

For example, if a view has only a 1:1 aspect ratio and a center position, Auto Layout still cannot infer how large it should be. You need something else, such as a fixed width, leading and trailing anchors, or a height from another layout relationship.

This is why ratio constraints usually appear beside ordinary sizing or edge constraints rather than replacing them.

Common Pitfalls

Forgetting translatesAutoresizingMaskIntoConstraints = false is a common reason programmatic constraints behave unpredictably.

Inverting the multiplier is another easy mistake. If you want 16:9, decide carefully whether you mean width = height * 16/9 or height = width * 9/16.

Adding too many size constraints can over-constrain the view. If you specify width, height, leading, trailing, and a ratio, the system may have conflicting instructions.

Finally, do not confuse an aspect ratio constraint with image scaling behavior. contentMode controls how image pixels fit inside the view, while Auto Layout controls the view’s frame.

Summary

  • an aspect ratio constraint keeps width and height in a fixed proportion
  • anchor-based constraints are the clearest modern API for creating one
  • a square view uses heightAnchor.constraint(equalTo: widthAnchor)
  • ratios such as 16:9 use a multiplier on one dimension relative to the other
  • ratio constraints need supporting position or size constraints to produce a complete layout

Course illustration
Course illustration

All Rights Reserved.