Oliver
Oliver

Reputation: 23510

UIView handling gestures, with inside UIButton that should catch touches

I have an UIView that contains a UIButton.
The UIView catches touch events using the following method :

[self.view addGestureRecognizer:[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(open:)] autorelease]];

In some conditions, I don't want to do anything when the view is touched :

- (void) open:(UITapGestureRecognizer *)recognizer
{
    if (self.someCondition == YES) return;
    // Do very interesting stuff
}

The UIButton is linked to a method like this :

[self.deleteButton addTarget:self action:@selector(deleteTheWorld:) forControlEvents:UIControlEventTouchUpInside];

The problem is that when someCondition = YES, the UIButton does not respond to touch events. How may I make it respond ?

Note : I only display the UIButton when someCondition == YES.

Upvotes: 0

Views: 797

Answers (2)

micantox
micantox

Reputation: 5616

I think your best option is to manage the button clicking in your open selector.

Just put something like

CGPoint location = [recognizer locationInView:self.view];
if(self.someCondition == YES) 
    if(recognizer.state == UIGestureRecognizerStateRecognized &&
       CGRectContainsPoint(self.deleteButton.frame, location))
         [self deleteTheWorld];
    else
         return;

instead of

- (void) open:(UITapGestureRecognizer *)recognizer
{
    if (self.someCondition == YES) return;
    // Do very interesting stuff
}

and of course you don't need to register the target action for the button then!

Upvotes: 0

danypata
danypata

Reputation: 10175

First of all try using tapRecognizer.cancelsTouchesInView = NO; if this won't work I suggest to use UIGestureRecognizerDelegate methods to prevent touches in your views something like:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
        if ([touch.view isKindOfClass:[UIButton class]]) {
              return YES; // button is touched then, yes accept the touch
        }
        else if (self.someContiditon == YES) {
            return NO; // we don't want to receive touch on the view because of the condition
        }
        else { 
          return YES; // tap detected on view but no condition is required
        }
  }

Upvotes: 2

Related Questions