删除UIButton的手势

时间:2014-04-10 07:03:08

标签: ios objective-c uibutton uigesturerecognizer uipangesturerecognizer

我正在使用UIGestureRecognizer进行平移,旋转,捏合。但我正在申请整个观点。我需要删除子视图以外的按钮的手势。但是,当我使用泛按钮也影响。如何限制按钮从self.view移动。我在UIPanGestureRecognizer下面使用了以下代码。

UIPanGestureRecognizer *dbpan = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                        action:@selector(ondbPan:)];

[self.view addGestureRecognizer:dbpan];

[closeButton removeGestureRecognizer:dbpan];

泛:

- (void)ondbPan:(UIPanGestureRecognizer *)gesture
{
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {


        CGPoint offset = [gesture translationInView:self.view];

        CGPoint center = gesture.view.center;
        center.x += offset.x;
        center.y += offset.y;
        gesture.view.center = center;

        [gesture setTranslation:CGPointZero inView:self.view];

    }
}

3 个答案:

答案 0 :(得分:5)

如果该子视图是UIButton类的类,请尝试使用UIGestureRecognizer的委托返回FALSE的下方代码。您还可以在设置并添加dbpan.delegate = self;时设置委托UIPanGestureRecognizer

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

         return TRUE;
      }
}

<强>更新: -

我不知道为什么不能在你的最后工作我测试这个创建一个演示以及使用这个代码: -

.h文件

@interface myviewcontroller : UIViewController<UIGestureRecognizerDelegate>

和.m class

- (void)pan:(UIPanGestureRecognizer *)gesture
{
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {

        CGPoint location = [gesture locationInView:self.view];

        [demoView setCenter:location];
    }
}

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

        return TRUE;
    }
}

- (void)viewDidLoad
{


    UIPanGestureRecognizer *dbpan = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                            action:@selector(pan:)];
    dbpan.delegate=self;
    [self.view addGestureRecognizer:dbpan];
    [super viewDidLoad];
}

-(IBAction)B1called
{

    NSLog(@"This is called button 1");

}
-(IBAction)B2called
{
     NSLog(@"This is called button 2");

}

它的输出是

enter image description here

答案 1 :(得分:0)

试试这个......

while (closeButton.gestureRecognizers.count) {
    [closeButton removeGestureRecognizer:[closeButton.gestureRecognizers objectAtIndex:0]];
}

答案 2 :(得分:0)

在Swift上:

func gestureRecognizer(gestureRecognizer:UIGestureRecognizer,shouldReceiveTouch touch:UITouch) - &gt;布尔{

if (touch.view!.isKindOfClass(UIButton)) {
    return false
}
return true
}

注意:确保在viewDidLoad()上添加了UIGestureRecognizerDelegate并tapGesture.delegate = self。