处理UIGestureRecognizer向左滑动

时间:2016-02-13 12:45:28

标签: ios objective-c uigesturerecognizer

我正在尝试使用以下代码添加手势识别器。

但是,手势无法识别。为了使视图控制器成为视图的委托 - 还是其他类似的东西,还有什么我需要做的吗?

我已在UIGestureRecognizerDelegate文件

中实施了.h协议
//in view did load
   UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
    rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [rightRecognizer setNumberOfTouchesRequired:1];
    [_myImage addGestureRecognizer:rightRecognizer];


    //........towards left Gesture recogniser for swiping.....//
    UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeHandle:)];
    leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [leftRecognizer setNumberOfTouchesRequired:1];
    [_myImage addGestureRecognizer:leftRecognizer];

//new methods
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
    //Do moving
    NSLog(@"Right Swipe performed");//not appearing
}

- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
    // do moving
    NSLog(@"Left Swipe performed");//not appearing
}

2 个答案:

答案 0 :(得分:3)

你需要的第一个

   _myImage.userInteractionEnabled=YES;

然后

  UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
  UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];

  // Setting the swipe direction.
  [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
  [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

   // Adding the swipe gesture on image view
   [_myImage addGestureRecognizer:swipeLeft];
   [_myImage addGestureRecognizer:swipeRight];

然后调用类似

的方法
 - (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {

   if (swipe.direction == UISwipeGestureRecognizerDirectionLeft)
      {
         NSLog(@"Left Swipe");
      }
     if (swipe.direction == UISwipeGestureRecognizerDirectionRight)
      {
        NSLog(@"Right Swipe");
     }
  }

我希望这会有效..

答案 1 :(得分:0)

在向图像视图添加手势之前,必须启用“_myImage”的用户交互: _myImage.userInteractionEnabled = YES;