Jeremy L
Jeremy L

Reputation: 3810

On iOS, why does the following UITapGestureRecognizer (Tap) not work?

If I just start a brand new Single View App project on Xcode 4.3.2, and use the following code:

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc] 
                              initWithImage:[UIImage imageNamed:@"pic.jpg"]];
    [self.view addSubview:imageView];

    self.view.userInteractionEnabled = YES;
    self.view.multipleTouchEnabled = YES;

    UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] 
                               initWithTarget:self action:@selector(handleTap:)];
    tapRecognizer.numberOfTapsRequired = 1;

    [imageView addGestureRecognizer:tapRecognizer];
}

-(void) handleTap:(UIGestureRecognizer *) gesture {
    NSLog(@"Image tapped on");
}

The handleTap method is never called even if I tap on the image... is something not done correctly here?

Upvotes: 0

Views: 258

Answers (2)

Vladimir
Vladimir

Reputation: 170849

You need to enable touches in your image view (as it is disabled by default), not in controller's view:

imageView.userInteractionEnabled = YES;

Upvotes: 4

Pieter
Pieter

Reputation: 1831

Is <UIGestureRecognizerDelegate> at the end of your @interface in your header file?

Upvotes: 0

Related Questions