Reputation: 11297
I have a grid of thumbnail images, and when one of them is touched, I'd like to show the whole image. Now, I know that UIImageView does not respond to touch events, but as suggested in this answer, I created a UIButton to handle the event. See code below:
- (void)displayImage
{
NSUInteger i = 0; // The actual code is different and works; this is just for brevity's sake.
// UILazyImageView is a subclass of UIImageView
UILazyImageView *imageView = [[UILazyImageView alloc] initWithURL:[NSURL URLWithString:[[[self images] objectAtIndex:i] thumbnailUrl]]];
UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imageButton setFrame:[imageView frame]];
[imageButton addTarget:self action:@selector(imageTapped:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:imageButton];
[[self containerView] addSubview:imageView];
[imageView release];
}
}
- (void)imageTapped:(id)sender
{
NSLog(@"Image tapped.");
// Get the index of sender in the images array
NSUInteger index = 0; // Don't worry, I know. I'll implement this later
FullImageViewController *fullImageViewController = [[[FullImageViewController alloc] initWithImageURL:[NSURL URLWithString:[[[self images] objectAtIndex:index] url]]] autorelease];
[[self navigationController] pushViewController:fullImageViewController animated:YES];
}
Ok. So I've create a custom button, set its frame to match the image frame, told it to respond to touch up inside and how to respond, and added it to the image's subviews. But when I run this, I get nothing. The "Image tapped." doesn't appear in the console, so I know that the message isn't being sent. What am I doing wrong here?
Many thanks for all your help.
Upvotes: 1
Views: 1782
Reputation: 1792
In addition to setting imageView.userInteractionEnabled = YES
, you can eliminate the button altogether and add a UITapGestureRecognizer
to the UIImageView
to handle taps. It would look something like:
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
[imageView addGestureRecognizer:recognizer];
Upvotes: 1
Reputation: 11174
by default UIImageView has its userInteractionEnabled property set to NO
add this line
imageView.userInteractionEnabled = YES;
Upvotes: 3
Reputation:
Try
imageView.userInteractionEnabled = YES;
This is a property inherited from UIView, but as per Apple's docs, UIImageView changes its default value to NO, ignoring all events.
Upvotes: 1