How can I detect interactions anywhere outside of UIControl, non-invasively?

I have a custom UIControl that, when listening, enters the confirmation state and, when it is used again, performs the required action.

I want this control to return to its original state if the user interacts somewhere else on the screen. Is there a non-invasive way to achieve this?

Clarification: I consider the code to be invasive if I cannot contain it inside this control. I would like to provide the developer of another application with this code, which they could use to add a control to their application, without having to mess with the code elsewhere in the application. If this is not possible, good, but the question is how to accomplish this non-invasively.

+4
source share
2 answers

You can think of a UITapGestureRecognizer placed on top of everything that triggers a reject only when a touch occurs outside your UIControl borders.

Sort of

 - (void)presentConfirm { // whatever self.dismissRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)]; self.dismissRecognizer = self; [self.view addGestureRecognizer:self.dismissRecognizer]; } - (void)dismiss:(UIGestureRecognizer *)gestureRecognizer { // do stuff [self.view removeGestureRecognizer:self.dismissRecognizer]; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { CGPoint touchPoint = [touch locationInView:self.view]; return !CGRectContainsPoint(self.control.frame, touch)); } 

Basically, you only run the dismiss method when the touch happens outside of the UIControl framework (I assumed that your control is listed as self.control ).

You will also need the dismissRecognizer property declared as

 @property (nonatomic, strong) UITapGestureRecognizer *dismissRecognizer; 

and to prevent warnings, you should also declare that your controller complies with the UIGestureRecognizerDelegate protocol.

+1
source

You can try to accomplish this using the touchhesBegan method:

 - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ if(myUIControl.isInConfirmState){ // check if your control is in confirmed state UITouch* touch = [touches anyObject]; CGPoint touchLocation = [touch locationInView:self.view]; if(!CGRectContainsPoint(myUIControl.frame, touchLocation)){ // set myUIControl to it initial state } } } 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1488535/


All Articles