How to assign an action for UIImageView object in Swift

IosSwiftUiimageview

Ios Problem Overview


I'm trying to assign an UIImageView to an action when the user taps it.

I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?

Ios Solutions


Solution 1 - Ios

You'll need a UITapGestureRecognizer. To set up use this:

override func viewDidLoad()
{
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}

@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let tappedImage = tapGestureRecognizer.view as! UIImageView
    
    // Your action
}

(You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)

Solution 2 - Ios

You need to add a a gesture recognizer (For tap use UITapGestureRecognizer, for tap and hold use UILongPressGestureRecognizer) to your UIImageView.

let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true

And Implement the selector method like:

@objc func tappedMe()
{
    println("Tapped on Image")
}

Solution 3 - Ios

You can add a UITapGestureRecognizer to the imageView, just drag one into your Storyboard/xib, Ctrl-drag from the imageView to the gestureRecognizer, and Ctrl-drag from the gestureRecognizer to the Swift-file to make an IBAction.

You'll also need to enable user interactions on the UIImageView, as shown in this image: enter image description here

Solution 4 - Ios

For Swift do this:

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
    imageView.addGestureRecognizer(tap)
    imageView.isUserInteractionEnabled = true
}

func tappedMe() {
    print("Tapped on Image")
}

Solution 5 - Ios

Swift4 Code

Try this some new extension methods:

import UIKit

extension UIView {
    
    fileprivate struct AssociatedObjectKeys {
        static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
    }
    
    fileprivate typealias Action = (() -> Void)?
    
    
    fileprivate var tapGestureRecognizerAction: Action? {
        set {
            if let newValue = newValue {
                // Computed properties get stored as associated objects
                objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            }
        }
        get {
            let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
            return tapGestureRecognizerActionInstance
        }
    }
    
    
    public func addTapGestureRecognizer(action: (() -> Void)?) {
        self.isUserInteractionEnabled = true
        self.tapGestureRecognizerAction = action
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        self.addGestureRecognizer(tapGestureRecognizer)
    }
    
    
    @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
        if let action = self.tapGestureRecognizerAction {
            action?()
        } else {
            print("no action")
        }
    }
    
}

Now whenever we want to add a UITapGestureRecognizer to a UIView or UIView subclass like UIImageView, we can do so without creating associated functions for selectors!

Usage:

 profile_ImageView.addTapGestureRecognizer {
        print("image tapped")
    }

Solution 6 - Ios

You could actually just set the image of the UIButton to what you would normally put in a UIImageView. For example, where you would do:

myImageView.image = myUIImage

You could instead use:

myButton.setImage(myUIImage, forState: UIControlState.Normal)

So, here's what your code could look like:

override func viewDidLoad(){
  super.viewDidLoad()
  
  var myUIImage: UIImage //set the UIImage here
  myButton.setImage(myUIImage, forState: UIControlState.Normal)
}

@IBOutlet var myButton: UIButton!
@IBAction func buttonTap(sender: UIButton!){
  //handle the image tap
}

The great thing about using this method is that if you have to load the image from a database, you could set the title of the button before you set the image:

myButton.setTitle("Loading Image...", forState: UIControlState.Normal)

To tell your users that you are loading the image

Solution 7 - Ios

Need to add lazy for TapGestureRecognizer to register
since the 'self' in UITapGestureRecognizer(target: self ...) will be nil if it's not a lazy var. Even if you set isUserInteractionEnable = true, it won't register without lazy var.

lazy var imageSelector : UIImageView = {
    let image = UIImageView(image: "imageName.png")
    //now add tap gesture
    image.isUserInteractionEnabled = true
    image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
    return image
}()
@objc private func handleImageSelector() {
    print("Pressed image selector")
}

Solution 8 - Ios

You can put a UIButton with a transparent background over top of the UIImageView, and listen for a tap on the button before loading the image

Solution 9 - Ios

Swift 4 Code


Step 1 In ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)
        
        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true
        
    }

It's Tested And Working Properly

Solution 10 - Ios

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
//ViewController is your current view controller    
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
    imageView.addGestureRecognizer(tap)
    imageView.isUserInteractionEnabled = true
}

// Need to ass objective-c annotation 
@objc
func tappedMe() {
    print("Tapped on Image")
}

Solution 11 - Ios

I suggest to place invisible(opacity = 0) button on your imageview and then handle interaction on button.

Solution 12 - Ios

This is what I found, much easier to setup.

Here is the YouTube video

  1. Open the Library, look for "Tap Gesture Recognizer" object.
  2. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions.
  3. Then go to the view controller, drag the same object to set the IBAction.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3706773View Question on Stackoverflow
Solution 1 - IosAseiderView Answer on Stackoverflow
Solution 2 - IosMidhun MPView Answer on Stackoverflow
Solution 3 - IosEmilView Answer on Stackoverflow
Solution 4 - IosAbhishek KumarView Answer on Stackoverflow
Solution 5 - IosRavindra_BhatiView Answer on Stackoverflow
Solution 6 - IosJojodmoView Answer on Stackoverflow
Solution 7 - IoscandylineView Answer on Stackoverflow
Solution 8 - Iosdepsch aliView Answer on Stackoverflow
Solution 9 - IosSachin RasaneView Answer on Stackoverflow
Solution 10 - IosAditya SharmaView Answer on Stackoverflow
Solution 11 - IoslevanView Answer on Stackoverflow
Solution 12 - IosdogteethView Answer on Stackoverflow