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:
- Using Storyboard (Interface Builder)
- Programmatically in Swift
2. Adding UIImageView via Storyboard
- Open Main.storyboard in Xcode.
- Drag and drop an
UIImageView
from the Object Library onto the view. - Set the image using the Attributes Inspector.
- Adjust the content mode (Aspect Fit, Fill, Scale to Fill).
- Create an IBOutlet in
ViewController.swift
:@IBOutlet weak var myImageView: UIImageView!
- 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
Feature | Code Example |
---|---|
Set Image | myImageView.image = UIImage(named: "example") |
Content Mode | myImageView.contentMode = .scaleAspectFit |
Rounded Corners | myImageView.layer.cornerRadius = 10 |
Border & Shadow | myImageView.layer.borderWidth = 2 |
Load from URL | URLSession or SDWebImage |
Tap Gesture | UITapGestureRecognizer |
Image Animation | animationImages & 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
? 🚀