UIView处理手势,内部UIButton应该捕捉触摸

时间:2013-07-01 22:05:40

标签: ios uiview uibutton touch uigesturerecognizer

我有一个包含UIButton的UIView UIView使用以下方法捕获触摸事件:

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

在某些情况下,触摸视图时我不想做任何事情:

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

UIButton链接到这样的方法:

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

问题是当someCondition = YES时,UIButton不响应触摸事件。我该如何回应?

注意:我只在someCondition == YES时显示UIButton。

2 个答案:

答案 0 :(得分:2)

首先尝试使用tapRecognizer.cancelsTouchesInView = NO;如果这不起作用我建议使用UIGestureRecognizerDelegate方法来阻止您的观点中的触摸:

- (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
        }
  }

答案 1 :(得分:0)

我认为您最好的选择是管理点按open选择器的按钮。

只需添加类似

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

而不是

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

当然,您不需要为该按钮注册目标操作!