Detect tap on UIImageView IOS

user1172579 picture user1172579 · Mar 25, 2014 · Viewed 13.6k times · Source

Am I doing something wrong? I can't detect the tap on the UIImageview. The UIImageView *myImage is create in storyboard. the code files are here : https://drive.google.com/folderview?id=0B2jWw-2wZC52NDBFZ2lXUTUzQXM&usp=sharing

File: ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIImageView *myImage;

@end

File: ViewController.m

#import "ViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIGestureRecognizer *tapGestureRecognizer = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tappedImage:)];
    [self.myImage addGestureRecognizer:tapGestureRecognizer];
    self.myImage.userInteractionEnabled = YES; // default is no for UIImageView

}

- (void)tappedImage:(UIGestureRecognizer *)gestureRecognizer {
    //UIImageView *myImage = (UIImageView *)gestureRecognizer.view;
    // do stuff;
    NSLog(@"it works");
}


@end

Answer

A J picture A J · Mar 25, 2014

I think you should use class UITapGestureRecognizer as:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
preArrowImage.userInteractionEnabled = YES;
[preArrowImage addGestureRecognizer:singleTap];

-(void)tapDetected{
NSLog(@"single Tap on imageview");

}