在UIButtons上禁用UIPanGestureRecognizer

时间:2014-05-27 15:37:20

标签: ios objective-c uibutton uipangesturerecognizer

我向UIPanGestureRecognizer添加了UIView,问题是当您选中UIButton内的UIPanGestureRecognizer仍处于启用状态时。如何仅在按钮上禁用UIPanGestureRecognizer

2 个答案:

答案 0 :(得分:6)

您需要拥有手势识别器(Reference for Delegate)的代理人。例如,您的视图控制器可以是符合协议 UIGestureRecognizerDelegate 的委托。这样你就可以使用这个方法:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

在您的代表中,以避免在特定视图中识别手势。

您可以通过以下方式创建手势并将其分配到某个视图(ARC假设):

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(someMethodName:)];
panGesture.delegate = self;

UIView *someView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
[someView addGestureRecognizer:panGesture];

在这里,您可以获得有关如何处理手势以及避免在您感兴趣的某些视图上收到手势的更多详细信息:

Event handling guide for iOS

基本上,您需要执行以下操作以防止按钮上的手势:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
 if ([touch view] == self.myButton){
    return NO;
 }

 return YES;
}

返回NO会导致手势失败并允许其他视图继续处理触摸。

您还可以检查[触摸视图]是否属于 UIButton ,以使其更加通用并避免与所有按钮进行比较。

答案 1 :(得分:2)

将委托分配给UIPanGestureRecognizer并覆盖方法:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return ! ([touch.view isKindOfClass:[UIButton class]]);
}