UIImageView
Swift programming
iOS development
programmatically create UI
Swift tutorial

How do you create a UIImage View Programmatically - Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Creating a UIImageView programmatically in UIKit is straightforward once you separate the concerns of creation, layout, and image loading. The main details that matter in practice are content mode, Auto Layout setup, and making sure remote image work does not block the main thread.

Create And Configure The Image View

The basic pattern is:

swift
1import UIKit
2
3final class ProfileViewController: UIViewController {
4    private let avatarImageView: UIImageView = {
5        let imageView = UIImageView(image: UIImage(named: "avatar-placeholder"))
6        imageView.translatesAutoresizingMaskIntoConstraints = false
7        imageView.contentMode = .scaleAspectFill
8        imageView.clipsToBounds = true
9        return imageView
10    }()
11
12    override func viewDidLoad() {
13        super.viewDidLoad()
14        view.backgroundColor = .systemBackground
15        view.addSubview(avatarImageView)
16    }
17}

That gives you a working image view object, but it still needs layout constraints or a frame.

Use Auto Layout For Most UIKit Screens

Programmatic UIKit code usually prefers Auto Layout:

swift
1override func viewDidLoad() {
2    super.viewDidLoad()
3    view.addSubview(avatarImageView)
4
5    NSLayoutConstraint.activate([
6        avatarImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24),
7        avatarImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
8        avatarImageView.widthAnchor.constraint(equalToConstant: 120),
9        avatarImageView.heightAnchor.constraint(equalToConstant: 120)
10    ])
11
12    avatarImageView.layer.cornerRadius = 60
13}

The critical line is translatesAutoresizingMaskIntoConstraints = false. Without it, Auto Layout constraints will fight the old autoresizing mask behavior.

Choose The Right Content Mode

The contentMode controls how the image is drawn in the view bounds:

  • '.scaleAspectFit keeps the full image visible'
  • '.scaleAspectFill fills the box and may crop'
  • '.center does not scale the image'

That choice matters more than many beginners expect. A lot of "my image is stretched" or "my image is cut off" issues are really content mode issues rather than loading problems.

For circular avatars, .scaleAspectFill plus clipsToBounds = true is a very common combination.

Load Remote Images Asynchronously

If the image comes from the network, do not load it synchronously on the main thread:

swift
1func loadImage(from url: URL) {
2    URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
3        guard let data, let image = UIImage(data: data) else { return }
4
5        DispatchQueue.main.async {
6            self?.avatarImageView.image = image
7        }
8    }.resume()
9}

UI updates still belong on the main thread, but the actual download does not.

For production apps, you usually add caching or use an image-loading library so repeated screens do not download the same file over and over.

Frame-Based Layout Still Exists

For very simple screens, a manual frame is still valid:

swift
1override func viewDidLayoutSubviews() {
2    super.viewDidLayoutSubviews()
3    avatarImageView.frame = CGRect(x: 20, y: 100, width: 100, height: 100)
4}

The important rule is not to mix frame-based layout and Auto Layout on the same view without understanding which one owns the final size and position.

Add Accessibility And Rendering Intent

For meaningful images, accessibility matters:

swift
avatarImageView.isAccessibilityElement = true
avatarImageView.accessibilityLabel = "Profile photo"

If you are using template-style icons, be explicit about rendering mode:

swift
let icon = UIImage(systemName: "star.fill")?.withRenderingMode(.alwaysTemplate)
avatarImageView.image = icon
avatarImageView.tintColor = .systemYellow

That is especially useful when the image view displays symbols rather than photos.

Common Pitfalls

One common mistake is forgetting to disable autoresizing mask translation before adding constraints.

Another issue is choosing the wrong content mode and then debugging the wrong part of the code.

A third problem is loading remote images on the main thread, which causes visible UI stalls.

Finally, in reusable cells, developers often forget to reset the image in reuse paths, which causes old images to flash during scrolling.

Summary

  • Create the UIImageView, configure it, then add it to the view hierarchy.
  • Use Auto Layout for most programmatic UIKit layouts.
  • Set contentMode deliberately because it controls cropping and scaling behavior.
  • Load remote images asynchronously and update the UI on the main thread.
  • Add accessibility labels and rendering configuration when the image is part of the UI meaning, not just decoration.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.