Anatoliy Gatt
Anatoliy Gatt

Reputation: 2491

Tap Recognition for UIImageView in the UITableViewCell

Currently I'm facing a problem, I would like to perform action when the UIImageView on my UITableViewCell had been tapped.

Question: How could I do it? Could any one show me the code, or any tutorial?

Thanks in advance!

Upvotes: 25

Views: 24562

Answers (5)

dimohamdy
dimohamdy

Reputation: 3053

Use ALActionBlocks to action in block

__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
    NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];

Upvotes: 0

WaaleedKhan
WaaleedKhan

Reputation: 685

Try this

//within cellForRowAtIndexPath (where customer table cell with imageview is created and reused)
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
tap.cancelsTouchesInView = YES;
tap.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:tap];

// handle method
- (void) handleImageTap:(UIGestureRecognizer *)gestureRecognizer 
{
    RKLogDebug(@"imaged tab");
}

make sure u have....

imageView.userInteractionEnabled = YES;

Upvotes: 6

Mick MacCallum
Mick MacCallum

Reputation: 130222

This is actually easier than you would think. You just need to make sure that you enable user interaction on the imageView, and you can add a tap gesture to it. This should be done when the cell is instantiated to avoid having multiple tap gestures added to the same image view. For example:

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod:)];

        [self.imageView addGestureRecognizer:tap];
        [self.imageView setUserInteractionEnabled:YES];
    }

    return self;
}

- (void)myTapMethod:(UITapGestureRecognizer *)tapGesture
{
    UIImageView *imageView = (UIImageView *)tapGesture.view;
    NSLog(@"%@", imageView);
}

Upvotes: 46

Bradley
Bradley

Reputation: 617

A tap gesture recogniser can be very memory hungry and can cause other things on the page to break. I would personally reconmend you create a custom table cell, insert a button into the custom cell frame and in the tableview code set the self.customtablecell.background.image to the image you want. This way you can assign the button an IBaction to make it push to whatever view you want.

Upvotes: 0

iArezki
iArezki

Reputation: 1271

you can use a customButton instead UIImageView

Upvotes: 3

Related Questions