Swift
UIImageView
iOS Development
Programming
SwiftUI

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 in code is a standard UIKit task when you want full control over layout, lifecycle, and reuse behavior. Programmatic setup is often clearer than storyboard wiring for reusable components and custom screens. A solid implementation includes initialization, constraints, content mode, async image loading, and accessibility.

Create the Image View in Code

Start with a deterministic UIKit setup: create the view, configure it, disable autoresizing-mask translation, and add constraints.

swift
1import UIKit
2
3final class ProfileViewController: UIViewController {
4    private let avatarImageView: UIImageView = {
5        let imageView = UIImageView()
6        imageView.translatesAutoresizingMaskIntoConstraints = false
7        imageView.contentMode = .scaleAspectFill
8        imageView.clipsToBounds = true
9        imageView.layer.cornerRadius = 48
10        imageView.backgroundColor = .secondarySystemBackground
11        return imageView
12    }()
13
14    override func viewDidLoad() {
15        super.viewDidLoad()
16        view.backgroundColor = .systemBackground
17
18        view.addSubview(avatarImageView)
19
20        NSLayoutConstraint.activate([
21            avatarImageView.widthAnchor.constraint(equalToConstant: 96),
22            avatarImageView.heightAnchor.constraint(equalToConstant: 96),
23            avatarImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24),
24            avatarImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
25        ])
26
27        avatarImageView.image = UIImage(named: "avatar-placeholder")
28    }
29}

This gives you a fully working image view without Interface Builder.

Pick the Right Content Mode

contentMode changes how the image is rendered inside the view bounds:

  • '.scaleAspectFit keeps the entire image visible'
  • '.scaleAspectFill fills the bounds and may crop'
  • '.center keeps the original size and centers the image'

For avatars, .scaleAspectFill is often the right choice. For diagrams, QR codes, or screenshots, .scaleAspectFit is usually safer because cropping can remove meaningful content.

Choosing the wrong content mode is one of the most common reasons an otherwise correct UIImageView looks wrong.

Load Remote Images Asynchronously

If the image comes from the network, never fetch it synchronously on the main thread. Load in the background and update the UI on the main thread.

swift
1import UIKit
2
3func loadImage(from url: URL, into imageView: UIImageView) {
4    URLSession.shared.dataTask(with: url) { data, _, error in
5        guard error == nil,
6              let data,
7              let image = UIImage(data: data) else {
8            return
9        }
10
11        DispatchQueue.main.async {
12            imageView.image = image
13        }
14    }.resume()
15}

That pattern keeps scrolling and touch interactions responsive while the image is loading.

Add Caching for Reuse

If the same images are shown repeatedly, a simple in-memory cache reduces duplicate network and decoding work.

swift
1import UIKit
2
3final class ImageLoader {
4    static let shared = ImageLoader()
5    private let cache = NSCache<NSURL, UIImage>()
6
7    func fetch(_ url: URL, completion: @escaping (UIImage?) -> Void) {
8        if let cached = cache.object(forKey: url as NSURL) {
9            completion(cached)
10            return
11        }
12
13        URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
14            guard let data, let image = UIImage(data: data) else {
15                DispatchQueue.main.async { completion(nil) }
16                return
17            }
18
19            self?.cache.setObject(image, forKey: url as NSURL)
20            DispatchQueue.main.async { completion(image) }
21        }.resume()
22    }
23}

This is especially important when image views live inside table-view or collection-view cells.

Handle Reuse and Accessibility

If the image view is part of a reusable cell, reset state in prepareForReuse so stale images do not flash during scrolling.

swift
1override func prepareForReuse() {
2    super.prepareForReuse()
3    imageView?.image = UIImage(named: "avatar-placeholder")
4}

Also add accessibility metadata when the image conveys meaning:

swift
avatarImageView.isAccessibilityElement = true
avatarImageView.accessibilityLabel = "User profile photo"
avatarImageView.accessibilityTraits = .image

Programmatic UI setup should include semantics, not just pixels.

UIKit First, Even in Mixed SwiftUI Projects

The article title is about Swift, but this is fundamentally a UIKit task. Even in apps that use SwiftUI heavily, programmatic UIImageView setup remains useful in legacy screens, wrappers, and custom components.

That means the same discipline still applies:

  • explicit layout
  • explicit async loading behavior
  • explicit reuse handling

The framework wrapper may change, but the view lifecycle concerns do not.

Common Pitfalls

The biggest pitfall is forgetting translatesAutoresizingMaskIntoConstraints = false before activating Auto Layout constraints.

Another common issue is setting the wrong contentMode, which causes unexpected stretching or cropping.

People also update the image view off the main thread after a network response, which can lead to UI bugs and hard-to-reproduce behavior.

Summary

  • Create UIImageView programmatically with explicit configuration and constraints.
  • Choose contentMode based on the actual image semantics.
  • Load remote images asynchronously and update the UI on the main thread.
  • Add caching and reuse handling for list-based interfaces.
  • Include accessibility metadata so the image view is usable, not just visible.

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.