【问题标题】:UIView handling gestures, with inside UIButton that should catch touchesUIView 处理手势,内部 UIButton 应该捕捉触摸
【发布时间】:2013-07-01 22:05:39
【问题描述】:

我有一个包含 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。

【问题讨论】:

  • 试试tapRecognizer.cancelsTouchesInView = NO;

标签: ios uiview uibutton touch uigesturerecognizer


【解决方案1】:

首先尝试使用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
        }
  }

【讨论】:

  • tapRecognizer.cancelsTouchesInView = NO;像魅力一样工作。谢谢!
【解决方案2】:

我认为您最好的选择是管理在您的 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
}

当然你不需要为按钮注册目标动作!

【讨论】:

  • 但我想这样做,我的按钮将变成一个简单的矩形,不再像按钮一样,不是吗?
  • 是的,你是对的。我在想那个。我想你已经有了解决方案!顺便说一句,我尝试时无法重现该问题,一切正常!
猜你喜欢
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2012-11-12
  • 2011-06-03
相关资源
最近更新 更多