Performing actions when selecting image from UI

684 views Asked by At

I have a UIView that has:

  1. Image View
  2. Text View
  3. Scroll View (it has multiple images which are dynamically created in run time)

what I need to do is: when I select an Image (either the first image ,or the one from the scroll view) a pop up window shall appear with the image inside.

I prepared the pop up view but now all I need is a way to identify the image being pressed by the user, so that I can call the pop up controller and view the image. thx in advanced.

1

There are 1 answers

5
user80755 On BEST ANSWER

Simple solution: Add tap gesture recognizer to every imageview. Then in gesture recognizer selector you can use view property of the sender, which is the view gesture is attached to.

Example:

    UIImageView* imageView1;

    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTaps:)];

/* The number of fingers that must be on the screen */
 tapGestureRecognizer.numberOfTouchesRequired = 1;

/* The total number of taps to be performed before the gesture is recognized */
tapGestureRecognizer.numberOfTapsRequired = 1;

then in handleTaps you can do the following

-(void) handleTaps:(UITapGestureRecognizer*)paramSender
{
   UIImageVIew* seletedImageView = paramSender.view;
 UIImage* image = selectImageView.image; //do whatever you want with image
}

*Don't forget to set imageView.userInteractionEnabled = YES;

swift tested code

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        var imageView1 : UIImageView
        var image1 : UIImage

        image1 = UIImage(named: "testImage")!
        imageView1 = UIImageView(image: image1)
       imageView1.tag = 1
        imageView1.frame = CGRectMake(10, 10, 100, 100)
        let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tapGesture.numberOfTouchesRequired = 1
        tapGesture.numberOfTapsRequired = 1
        imageView1.userInteractionEnabled = true

        imageView1.addGestureRecognizer(tapGesture)

        self.view.addSubview(imageView1)
    }
    func handleTap(sender: UITapGestureRecognizer) {
        var imageView : UIImageView = sender.view as UIImageView
        var image : UIImage = imageView.image!
        println("Taped UIImageVIew"+String( imageView.tag))
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}