Reputation: 2134
I have been trying to play around with the touchedBegan, and touchedEnded. I basically am just trying to create an image in my view. Then be able to do something when the user touches the image. When I touch the image It does ever execute the code inside my if statement. Any idea on what I am doing wrong?
viewDidload:
UIImage *image = [UIImage imageNamed:@"myimage1.png"];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 320, 200);
[self.view addSubview:imageView];
imageViewsArray = [NSArray arrayWithObjects:imageView, nil];
touchesEnded:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// do this on touch
UIView *touchedView = [touch view];
if ([imageViewsArray indexOfObject:touchedView] != NSNotFound) {
// not not found means found!
NSLog(@"Got Touch!");
}
}
I also tried using this if statement:
if ([[touch view] isKindOfClass:[UIImageView class]]) {
NSLog(@"Got Touch 2!");
}
Upvotes: 1
Views: 588
Reputation: 11537
Like DrummerB said i will recommend using the UITapGestureRecognizer
instead. Have a look to the official doc here to get a good understanding of how it works but the main thing is to associate a gesture recognizer to the view that will handle the tap. In your case since you are dealing with a UIImageView
make sure that you turn on the property userInteractionEnabled
this is set to NO
by default for the UIImageView
: in another word the imageView are not picking up event by default.
Upvotes: 1
Reputation: 40201
If you want to be notified about a tap on your image view I recommend using a simpler approach using an UITapGestureRecognizer
.
// After initializing and adding your UIImageView:
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
[imageView addGestureRecognizer:gr];
- (void)handleTap:(UITapGestureRecognizer *)gr {
NSLog(@"Touched!");
}
If you want to stick with touchesEnded
, try these steps:
imageViews
array is not nil
in touchesEnded
.[touch view]
to see which view is receiving the touch.Upvotes: 1