Friday, October 12, 2012

How to add Tap Event to UIImageView in XCode?


This blog post is about adding tap event to UIImageView dynamically.

Here we can use UITapGestureRecognizer class. Checkput the following code.

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
        tap.cancelsTouchesInView = YES;
        tap.numberOfTapsRequired = 1;

Above code is to identify single tap on image. If you want to do it for double tap just increase the count by one in numberOfTapsRequired.

Now let's create our image view.

NSString *urlString = @"";
NSURL *url = [NSURL URLWithString:urlString];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
UIView* mainServiceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
imageView.userInteractionEnabled =TRUE;

Here note the last line imageView.userInteractionEnabled =TRUE; This is necessary else it will not respond to any gesture. Now add a gesture to image

[imagView addGestureRecognizer:tap];

Also add handleImageTap function to your view controller file.

- (void) handleImageTap:(UIGestureRecognizer *)gestureRecognizer {
    UIView* view = gestureRecognizer.view;
    //object of view which invoked this 

That's it now user can tap on your image.

Hope this helps you.

No comments:

Post a Comment