Piero
Piero

Reputation: 9273

Detect touch on UIImageView in a CustomCell

i have custom UITableViewCell, i have subclassed the UITableViewCell:

MyCustomCell.h

MyCustomCell:UITableViewCell

and then i have also a xib file for this custom cell, all work fine, i can show all information, and image i have added on the cell, but i want detect a touch when the user touch on the uiimageview, so i have tried in this way:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"MasterView";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[MasterViewCell alloc] init];
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MasterViewCustomCellImage" owner:self options:nil];
    cell = (MasterViewCell *)[nib objectAtIndex:0];
    //NSLog(@"Nuova Cella");
}

[self configureCell:cell atIndexPath:indexPath];

return cell;
}

 - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
 {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

UIImageView *thumbnailImage = (UIImageView *)[cell viewWithTag:1007];
[thumbnailImage setImage:[managedObject valueForKey:@"myImage"]];

if (thumbnailImage) {

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(detectTouchImage)];
    [longPress setMinimumPressDuration:1.0];
    [thumbnailImage setUserInteractionEnabled:YES];
    [thumbnailImage addGestureRecognizer:longPress];
}

 }

-(void)detectTouchImage
{
 NSLog(@"Image Pressed");
 }

but i can't understand why don't work, it enter in the thumbnailImage if, but there don't detect any gesture on the image...anyone can help me? i have tried it on ios 5 and ios 6, but don't work...

Upvotes: 2

Views: 1114

Answers (2)

Valeriy Van
Valeriy Van

Reputation: 1865

Just made test project to verify where is the problem.
Completely working example is here on GitHub. Download and play with it. TableViewCell has custom UIImageView with UILongPressGestureRecognizer attached to it. Everything is working just fine. Long press on any image and UIIAllertView pops up. So, your code with UILongPressGestureRecognizer seems to be OK. Problems is in some other part of your project which you don't expose.

Upvotes: -1

Igor N
Igor N

Reputation: 381

The problem is most probably that the cell is highjacking the touches. Can you check whether your didSelectCellForRow method is getting called or the row is highlighted when you tap it? Also try to assign the UILongPressGestureRecognizer to the cell rather than the image. If that works but you want to invoke the tap only when the thumb image is tapped you can use the locationInView method implemented in the UIGestureRecognizer class to see where exactly the user has tapped.

Upvotes: 0

Related Questions