swift
xcode
uiimageview
programming
ios-development

Programmatically set image to UIImageView with Xcode 6.1/Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Assigning an image to a UIImageView is simple in UIKit, but blank images usually come from setup problems rather than from the assignment itself. The main jobs are loading a valid UIImage, putting the image view into the hierarchy, and giving it layout and content-mode settings that make the image visible.

Set an Image from the Asset Catalog

If the image is bundled with the app, the most direct approach is to load it by name and assign it to the image property.

swift
1import UIKit
2
3final class BannerViewController: UIViewController {
4    private let imageView = UIImageView()
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8
9        view.backgroundColor = .systemBackground
10        imageView.translatesAutoresizingMaskIntoConstraints = false
11        imageView.contentMode = .scaleAspectFit
12        imageView.image = UIImage(named: "hero-banner")
13
14        view.addSubview(imageView)
15        NSLayoutConstraint.activate([
16            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
17            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
18            imageView.widthAnchor.constraint(equalToConstant: 220),
19            imageView.heightAnchor.constraint(equalToConstant: 220)
20        ])
21    }
22}

UIImage(named:) returns an optional. If the asset name is misspelled or missing from the bundle, the result is nil and the view shows nothing.

Assign an Image to an Outlet-Based Image View

If the image view already exists in a storyboard or nib, connect an outlet and assign the image after the view has loaded.

swift
1import UIKit
2
3final class ProfileViewController: UIViewController {
4    @IBOutlet private weak var avatarImageView: UIImageView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        avatarImageView.contentMode = .scaleAspectFill
9        avatarImageView.image = UIImage(named: "default-avatar")
10    }
11}

This is the same operation with less view construction code. The main difference is that storyboard layout already provides the frame and constraints.

Loading an Image from Disk or Data

When the image is not in the app bundle, create the UIImage from data instead of using an asset name.

swift
1import UIKit
2
3func loadSavedPhoto(into imageView: UIImageView) {
4    guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
5        return
6    }
7
8    let imageURL = documents.appendingPathComponent("profile.jpg")
9
10    guard let data = try? Data(contentsOf: imageURL),
11          let image = UIImage(data: data) else {
12        return
13    }
14
15    imageView.image = image
16}

This is common for user-generated photos, cached downloads, or edited images saved locally by the app.

Load Remote Images Without Blocking the UI

Network image loading should happen asynchronously. UIKit updates still belong on the main thread.

swift
1import UIKit
2
3@MainActor
4final class PhotoViewController: UIViewController {
5    @IBOutlet private weak var imageView: UIImageView!
6
7    override func viewDidLoad() {
8        super.viewDidLoad()
9
10        Task {
11            await fetchImage()
12        }
13    }
14
15    private func fetchImage() async {
16        guard let url = URL(string: "https://example.com/avatar.png") else {
17            return
18        }
19
20        do {
21            let (data, _) = try await URLSession.shared.data(from: url)
22            imageView.image = UIImage(data: data)
23        } catch {
24            print("image download failed: \(error)")
25        }
26    }
27}

This keeps the interface responsive while the download happens.

Make the Image View Actually Display Correctly

The image assignment itself is only half the story. contentMode controls whether the image fits, fills, or centers inside the view. Constraints determine whether the image view has a real size. Background color can help during debugging because it shows whether the image view exists even when the image is missing.

A very common debugging step is to set a visible frame or obvious constraints and give the image view a temporary background color. If the colored box appears but the image does not, the problem is image loading. If the box does not appear, the problem is layout.

Common Pitfalls

The most common issue is a wrong asset name. UIImage(named:) fails quietly by returning nil.

Developers also forget that the image view needs size. A correct image assignment still shows nothing if the view has zero width or height.

Loading remote data on the main thread causes UI stalls. Fetch asynchronously and update the image view on the main thread.

Summary

  • Set an image programmatically by assigning a UIImage to imageView.image.
  • Use UIImage(named:) for bundled assets and UIImage(data:) for file or network data.
  • Make sure the image view is in the view hierarchy and has real layout constraints.
  • Check contentMode, asset name, and thread usage when the image does not appear.

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.