Reputation: 38
I have a UIButton, I have added a action Touch up outside. I have a UIImageView.
I want the following action: when the user touches the button and releases at the UIImageView, I want someAction to be performed.
If the user touches the button and releases in the other view not in the UIImageView, someAction shouldn't be performed.
Here is my code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
NSLog(@"Touch x : %f y : %f", location.x, location.y);
if(CGRectContainsPoint(redBtn.frame, location)){
NSLog(@"red button pressed");
}else if (CGRectContainsPoint(blueBtn.frame, location)){
NSLog(@"blue button pressed");
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
if(CGRectContainsPoint(firstImageView.frame, location)){
if(redFlag){
[firstImageView setBackgroundColor:[UIColor redColor]];
}
else if(blueFlag){
[firstImageView setBackgroundColor:[UIColor blueColor]];
}
NSLog(@"touch ended in first view");
}else if(CGRectContainsPoint(secondImageView.frame, location)){
if(redFlag){
[secondImageView setBackgroundColor:[UIColor redColor]];
}
else if(blueFlag){
[secondImageView setBackgroundColor:[UIColor blueColor]];
}
NSLog(@"touch ended in second view");
}
}
Upvotes: 0
Views: 394
Reputation: 2523
Use touchesEnded
to implement this. To check button pressed or not use a BOOL and then at touch ended, use touch.view == imageView
then do required thing.
On button click event make a BOOL variable yes to ensure that it is pressed. Now, in touchesEnded of UIResponser write
UITouch *touch = [touches anyObject];
if (touch.view == imageView)
{
// do the required thing here
}
Upvotes: 1