iOS

⌘K
  1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Image Views (UIImageView)

Image Views (UIImageView)

What is UIImageView?

UIImageView is a UIKit component used to display images in an iOS app. It supports static images, animated images, content mode adjustments, and image rendering effects.


1. Creating a UIImageView

You can add a UIImageView in two ways:

  1. Using Storyboard (Interface Builder)
  2. Programmatically in Swift

2. Adding UIImageView via Storyboard

  1. Open Main.storyboard in Xcode.
  2. Drag and drop an UIImageView from the Object Library onto the view.
  3. Set the image using the Attributes Inspector.
  4. Adjust the content mode (Aspect Fit, Fill, Scale to Fill).
  5. Create an IBOutlet in ViewController.swift: @IBOutlet weak var myImageView: UIImageView!
  6. Modify properties in viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() myImageView.image = UIImage(named: "exampleImage") myImageView.contentMode = .scaleAspectFit }

3. Creating UIImageView Programmatically

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create UIImageView
        let myImageView = UIImageView()
        myImageView.image = UIImage(named: "exampleImage")
        myImageView.contentMode = .scaleAspectFit
        myImageView.layer.cornerRadius = 10
        myImageView.clipsToBounds = true

        // Enable Auto Layout
        myImageView.translatesAutoresizingMaskIntoConstraints = false

        // Add to View
        view.addSubview(myImageView)

        // Set Constraints
        NSLayoutConstraint.activate([
            myImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myImageView.widthAnchor.constraint(equalToConstant: 200),
            myImageView.heightAnchor.constraint(equalToConstant: 200)
        ])
    }
}

Explanation:

  • Loads an image named "exampleImage" from assets.
  • Uses scaleAspectFit to maintain aspect ratio.
  • Adds rounded corners and enables Auto Layout.

4. UIImageView Customization

4.1 Changing Image Dynamically

myImageView.image = UIImage(named: "newImage")

4.2 Adjusting Content Mode

myImageView.contentMode = .scaleAspectFit  // Maintains aspect ratio

Other options:

  • .scaleAspectFill (Crops to fill the view)
  • .scaleToFill (Stretches to fit)

4.3 Adding Rounded Corners

myImageView.layer.cornerRadius = 10
myImageView.clipsToBounds = true

4.4 Adding Borders

myImageView.layer.borderWidth = 2
myImageView.layer.borderColor = UIColor.red.cgColor

4.5 Applying Shadows

myImageView.layer.shadowColor = UIColor.black.cgColor
myImageView.layer.shadowOpacity = 0.5
myImageView.layer.shadowOffset = CGSize(width: 5, height: 5)
myImageView.layer.shadowRadius = 5

4.6 Making an Image Circular

myImageView.layer.cornerRadius = myImageView.frame.size.width / 2
myImageView.clipsToBounds = true

5. Loading Images from a URL

To load an image from the internet, use URLSession:

func loadImage(from urlString: String) {
    guard let url = URL(string: urlString) else { return }
    
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url),
           let image = UIImage(data: data) {
            DispatchQueue.main.async {
                self.myImageView.image = image
            }
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    loadImage(from: "https://example.com/image.jpg")
}

Best Practice: Use SDWebImage for caching:

import SDWebImage
myImageView.sd_setImage(with: URL(string: "https://example.com/image.jpg"), completed: nil)

6. UIImageView with Tap Gesture

To detect when the user taps an image:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer(tapGesture)

@objc func imageTapped() {
    print("Image was tapped!")
}

Enable isUserInteractionEnabled for gestures to work.


7. UIImageView with Animation

7.1 Animating Between Multiple Images

myImageView.animationImages = [
    UIImage(named: "image1")!,
    UIImage(named: "image2")!,
    UIImage(named: "image3")!
]
myImageView.animationDuration = 2.0  // Animation speed
myImageView.startAnimating()

7.2 Fade-In Effect

UIView.transition(with: myImageView, duration: 0.5, options: .transitionCrossDissolve, animations: {
    self.myImageView.image = UIImage(named: "newImage")
}, completion: nil)

8. UIImageView Example: Profile Picture with Edit Button

let profileImageView = UIImageView()
profileImageView.image = UIImage(named: "profile")
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 50
profileImageView.layer.borderWidth = 2
profileImageView.layer.borderColor = UIColor.white.cgColor
profileImageView.clipsToBounds = true
profileImageView.translatesAutoresizingMaskIntoConstraints = false

let editButton = UIButton(type: .system)
editButton.setTitle("Edit", for: .normal)
editButton.addTarget(self, action: #selector(editProfile), for: .touchUpInside)

view.addSubview(profileImageView)
view.addSubview(editButton)

NSLayoutConstraint.activate([
    profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    profileImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
    profileImageView.widthAnchor.constraint(equalToConstant: 100),
    profileImageView.heightAnchor.constraint(equalToConstant: 100),
    
    editButton.centerXAnchor.constraint(equalTo: profileImageView.centerXAnchor),
    editButton.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 10)
])

This creates a profile picture UI with an “Edit” button.


9. Summary

FeatureCode Example
Set ImagemyImageView.image = UIImage(named: "example")
Content ModemyImageView.contentMode = .scaleAspectFit
Rounded CornersmyImageView.layer.cornerRadius = 10
Border & ShadowmyImageView.layer.borderWidth = 2
Load from URLURLSession or SDWebImage
Tap GestureUITapGestureRecognizer
Image AnimationanimationImages & startAnimating()

Conclusion

  • UIImageView is essential for displaying images in iOS apps.
  • Supports content mode, gestures, animations, and network images.
  • Use lazy loading (SDWebImage) for better performance.

Would you like a complete gallery app example using UIImageView? 🚀