UIImageView
Swift
iOS Development
User Interaction
Code Tutorial

How to assign an action for UIImageView object in Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

UIImageView does not handle taps by default because user interaction is disabled on image views unless you enable it. To assign an action, attach a gesture recognizer and route the callback to your handler method. This is the standard, maintainable way to make images interactive in UIKit.

Basic Tap Action with Gesture Recognizer

A minimal setup enables interaction and attaches a tap recognizer.

swift
1import UIKit
2
3final class PhotoViewController: UIViewController {
4    private let imageView = UIImageView(image: UIImage(systemName: "photo"))
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        view.backgroundColor = .systemBackground
9
10        imageView.translatesAutoresizingMaskIntoConstraints = false
11        imageView.contentMode = .scaleAspectFit
12        imageView.isUserInteractionEnabled = true
13
14        let tap = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
15        imageView.addGestureRecognizer(tap)
16
17        view.addSubview(imageView)
18        NSLayoutConstraint.activate([
19            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
20            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
21            imageView.widthAnchor.constraint(equalToConstant: 120),
22            imageView.heightAnchor.constraint(equalToConstant: 120)
23        ])
24    }
25
26    @objc private func imageTapped() {
27        print("Image tapped")
28    }
29}

Without isUserInteractionEnabled = true, the recognizer callback will not fire.

Supporting Multiple Image Actions

If a screen has several interactive image views, assign tags or keep mapping structures for handlers.

swift
1@objc private func handleImageTap(_ sender: UITapGestureRecognizer) {
2    guard let view = sender.view else { return }
3    switch view.tag {
4    case 1:
5        print("Avatar tapped")
6    case 2:
7        print("Banner tapped")
8    default:
9        print("Unknown image tapped")
10    }
11}

This keeps event routing simple and avoids creating many nearly identical methods.

Adding Visual Feedback

Interactive images should provide feedback so users know tap was registered.

swift
1@objc private func imageTapped() {
2    UIView.animate(withDuration: 0.12, animations: {
3        self.imageView.alpha = 0.6
4    }, completion: { _ in
5        UIView.animate(withDuration: 0.12) {
6            self.imageView.alpha = 1.0
7        }
8    })
9}

Subtle feedback improves usability, especially on dense screens.

Accessibility Considerations

If an image acts like a button, expose it as such for accessibility.

swift
imageView.isAccessibilityElement = true
imageView.accessibilityLabel = "Open profile photo"
imageView.accessibilityTraits = .button

This helps VoiceOver users understand intended interaction.

Gesture Conflicts and Container Views

Interactive images often live inside scroll views, stack views, or collection cells. In these cases, gesture recognizers can conflict with parent gestures unless configured carefully.

A common fix is implementing recognizer delegate methods.

swift
1import UIKit
2
3final class InteractiveImageViewController: UIViewController, UIGestureRecognizerDelegate {
4    let imageView = UIImageView(image: UIImage(systemName: "star"))
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        imageView.isUserInteractionEnabled = true
9
10        let tap = UITapGestureRecognizer(target: self, action: #selector(onTap))
11        tap.delegate = self
12        imageView.addGestureRecognizer(tap)
13    }
14
15    @objc private func onTap() {
16        print("tap handled")
17    }
18
19    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
20        return false
21    }
22}

Also verify cell reuse behavior in collection views so recognizers are not attached multiple times. Duplicate recognizers can trigger repeated callbacks and unpredictable UX.

For analytics, emit one structured event per successful tap with screen and element identifiers. Avoid firing events on failed gesture recognitions to keep metrics trustworthy. This helps product teams analyze engagement accurately without inflating counts from gesture conflicts.

If taps trigger navigation, debounce rapid repeated taps to avoid duplicate push transitions. This is especially important on slower devices where animation timing can allow unintended double actions.

A small cooldown window often solves this without harming responsiveness.

Measure before and after to verify UX impact.

Common Pitfalls

A common pitfall is forgetting to enable user interaction on the image view.

Another issue is attaching recognizer to parent view instead of specific image, causing confusing tap behavior.

Developers also forget accessibility traits, leaving interactive images undiscoverable for assistive technologies.

Finally, avoid overload of hidden gesture areas that conflict with scroll views and other controls.

Summary

  • Enable isUserInteractionEnabled before expecting tap actions.
  • Use UITapGestureRecognizer for clean image interaction handling.
  • Organize multi-image tap routing with tags or mapping.
  • Provide visual and accessibility feedback for interactive images.
  • Test gesture interactions alongside scroll and container views.

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.