Recognize Tap on UIImageView inside customized UITableViewCell

Hi,
I have a customized UITableViewCell with several UIImageViews inside. Now, I
want to make the image fullscreen when the user taps on it. So, first, I need
recognize the tap using a UITapGestureRecognizer. I already failing here.
That’s my code:

method CustomTableViewCell.configureCell;
begin    
  {...}
  for n:= 0 to aArray.Images.Count-1 do
  begin
    var image:= UIImageView.alloc.initWithImage(aArray.Images[n].Image); 

    var tap:= new UITapGestureRecognizer WithTarget(self) action(selector(imageTapped:));
    image.userInteractionEnabled:= true;
    image.addGestureRecognizer(tap);
    
    var picWidth:= aArray.Images[n].Width;
    var picHeight:= aArray.Images[n].Height;
    var picX:= (cellWidth/2)-(picWidth/2);
    image.frame:= CGRectMake(picX,lastY,picWidth,picHeight);      
    self.contentView.addSubview(image);
  end;
  {...}
end;

The problem is that imageTapped is never called. If I add the GestureRecognizer to the whole cell then the method will be called.

You know what I’m doing wrong?

Best regards
Benny

I’m guessing the UITableView handles/swallows tapping. Have you tried just responding to

tableView() didSelectItemAtIndexPath()?

But then I’m checking if the cell was tapped and not only the image. I have several images inside a cell. So I need to differentiate.

For example you can implement the UIGestureRecognizer method “locationInView” to determine the touched UI element.

  • (CGPoint)locationInView:(UIView *)view

Mhm, I think thats not the most beautiful solution. I found another one that should work (but it doesn’t):
How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?

for each imageView: UIImageView in cell.contentView.subviews do
  if view.isKindOfClass(UIImageView.&class()) then
  begin
    var tap: UITapGestureRecognizer := UITapGestureRecognizer.alloc().initWithTarget(self) action(selector(imageTapped:));
    tap.setNumberOfTapsRequired(1);
    imageView.addGestureRecognizer(tap);
  end;

The idea was adding this loop to cellForRowAtIndexPath.
I also figured out that adding the recognizer to the contentView of the cell doesn’t work either.

I think, creating endles GestureRecognizer instances isn’t the best practice.
The cell class should handle it’s UI interaction itself. What means: Keep the cells logic inside the cell class. CellForRowAtIndexPath is Controller logic and should be separated from the cell.

Could you extract and post a small example project?
I’ll take a look on it and try to find a good solution.

I’m planning to add an UITableView community example shorty. It will contain many technics around the UITableView. I’ll add my “cell image tap solution” to that demo too.

1 Like