简体   繁体   中英

Touch Up Outside event recorded when pressed a UIImageView

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");
    }

}

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
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM