UIImageView
iOS development
Swift programming
image handling
mobile app development

How can I change the image displayed in a UIImageView programmatically?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

To change the image in a UIImageView programmatically in Swift, assign a new UIImage to its image property: imageView.image = UIImage(named: "newPhoto"). Images can be loaded from the asset catalog, the app bundle, a file path, remote URLs, SF Symbols, or generated from Data. For animated transitions, wrap the assignment in UIView.transition(with:).

Loading from Asset Catalog

The most common approach — load images added to Assets.xcassets:

swift
1let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
2
3// Load from asset catalog
4imageView.image = UIImage(named: "profilePhoto")
5
6// Change to a different image
7imageView.image = UIImage(named: "defaultAvatar")
8
9// Set content mode for proper scaling
10imageView.contentMode = .scaleAspectFit

UIImage(named:) caches the image in memory. Use UIImage(named:in:compatibleWith:) for images in specific bundles.

Loading from SF Symbols (iOS 13+)

swift
1// System symbols
2imageView.image = UIImage(systemName: "heart.fill")
3
4// With configuration
5let config = UIImage.SymbolConfiguration(pointSize: 30, weight: .bold)
6imageView.image = UIImage(systemName: "star.fill", withConfiguration: config)
7
8// Tint color
9imageView.tintColor = .systemRed
10imageView.image = UIImage(systemName: "heart.fill")

Loading from File Path

swift
1// From the app bundle
2if let path = Bundle.main.path(forResource: "background", ofType: "png") {
3    imageView.image = UIImage(contentsOfFile: path)
4}
5
6// From Documents directory
7let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
8let imagePath = documentsPath.appendingPathComponent("saved_photo.jpg")
9imageView.image = UIImage(contentsOfFile: imagePath.path)

UIImage(contentsOfFile:) does not cache the image, making it better for large images that should not stay in memory.

Loading from URL (Async)

Load images from remote URLs using URLSession:

swift
1func loadImage(from url: URL, into imageView: UIImageView) {
2    URLSession.shared.dataTask(with: url) { data, response, error in
3        guard let data = data, error == nil,
4              let image = UIImage(data: data) else { return }
5
6        DispatchQueue.main.async {
7            imageView.image = image
8        }
9    }.resume()
10}
11
12// Usage
13if let url = URL(string: "https://example.com/photo.jpg") {
14    loadImage(from: url, into: imageView)
15}

Using async/await (iOS 15+)

swift
1func loadImage(from url: URL) async throws -> UIImage {
2    let (data, _) = try await URLSession.shared.data(from: url)
3    guard let image = UIImage(data: data) else {
4        throw URLError(.cannotDecodeContentData)
5    }
6    return image
7}
8
9// Usage
10Task {
11    if let url = URL(string: "https://example.com/photo.jpg") {
12        imageView.image = try? await loadImage(from: url)
13    }
14}

Loading from Data

swift
1// From Data object (e.g., from camera, network, or Core Data)
2let imageData: Data = ...  // JPEG or PNG data
3imageView.image = UIImage(data: imageData)
4
5// From Base64 string
6let base64String = "iVBORw0KGgoAAAANSUhEUg..."
7if let data = Data(base64Encoded: base64String) {
8    imageView.image = UIImage(data: data)
9}

Animated Transitions

Smoothly transition between images using UIView animations:

swift
1// Crossfade transition
2UIView.transition(with: imageView,
3                  duration: 0.3,
4                  options: .transitionCrossDissolve,
5                  animations: {
6                      self.imageView.image = UIImage(named: "newImage")
7                  })
8
9// Flip transition
10UIView.transition(with: imageView,
11                  duration: 0.5,
12                  options: .transitionFlipFromLeft,
13                  animations: {
14                      self.imageView.image = UIImage(named: "backSide")
15                  })

Available transition options: .transitionCrossDissolve, .transitionFlipFromLeft, .transitionFlipFromRight, .transitionCurlUp, .transitionCurlDown.

Setting Up UIImageView Programmatically

swift
1class ViewController: UIViewController {
2    private let imageView: UIImageView = {
3        let iv = UIImageView()
4        iv.contentMode = .scaleAspectFill
5        iv.clipsToBounds = true
6        iv.layer.cornerRadius = 12
7        iv.translatesAutoresizingMaskIntoConstraints = false
8        return iv
9    }()
10
11    override func viewDidLoad() {
12        super.viewDidLoad()
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: 200),
19            imageView.heightAnchor.constraint(equalToConstant: 200)
20        ])
21
22        imageView.image = UIImage(named: "placeholder")
23    }
24
25    func updateImage(to name: String) {
26        imageView.image = UIImage(named: name)
27    }
28}

UIImageView in Interface Builder

If the UIImageView is connected via @IBOutlet:

swift
1class ProfileViewController: UIViewController {
2    @IBOutlet weak var avatarImageView: UIImageView!
3
4    override func viewDidLoad() {
5        super.viewDidLoad()
6        avatarImageView.image = UIImage(named: "defaultAvatar")
7    }
8
9    @IBAction func changePhotoTapped(_ sender: UIButton) {
10        avatarImageView.image = UIImage(named: "newPhoto")
11    }
12}

Common Pitfalls

  • Updating image from a background thread: UIKit must be updated on the main thread. Setting imageView.image from a URLSession completion handler without DispatchQueue.main.async causes crashes or visual glitches.
  • Using UIImage(named:) for large images that should not be cached: UIImage(named:) caches images in memory permanently during the app session. For large images (photos, backgrounds), use UIImage(contentsOfFile:) which does not cache and frees memory when the image is deallocated.
  • Forgetting to set contentMode: The default contentMode is .scaleToFill, which stretches the image to fill the view, distorting the aspect ratio. Use .scaleAspectFit (fits within bounds) or .scaleAspectFill (fills bounds, may crop) with clipsToBounds = true.
  • Image name typo returning nil silently: UIImage(named: "nonexistent") returns nil without an error. The image view shows nothing, and no crash or warning occurs. Double-check asset names match exactly (case-sensitive).
  • Not handling optional UIImage from network loads: Network requests can fail, return non-image data, or time out. Always use guard let or if let when creating UIImage(data:) and provide a placeholder image for failure cases.

Summary

  • Set imageView.image = UIImage(named: "name") to change the displayed image
  • Use UIImage(named:) for asset catalog images (cached) and UIImage(contentsOfFile:) for large files (not cached)
  • Load remote images with URLSession and always update imageView.image on the main thread
  • Use UIView.transition(with:duration:options:animations:) for smooth image change animations
  • Set contentMode to .scaleAspectFit or .scaleAspectFill to maintain proper aspect ratio

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.