博客> iOS用一个pan手势实现上下左右不同方向的移动事件
iOS用一个pan手势实现上下左右不同方向的移动事件
2017-12-11 09:24 评论:0 阅读:428 Edward比伯
ios 移动手势pan swipe
  • @interface ViewController ()

@end

@implementation ViewController //用一个pan手势代替上下左右滑动

  • (void)pan:(UIPanGestureRecognizer *)sender { typedef NS_ENUM(NSUInteger, UIPanGestureRecognizerDirection) { UIPanGestureRecognizerDirectionUndefined, UIPanGestureRecognizerDirectionUp, UIPanGestureRecognizerDirectionDown, UIPanGestureRecognizerDirectionLeft, UIPanGestureRecognizerDirectionRight }; static UIPanGestureRecognizerDirection direction = UIPanGestureRecognizerDirectionUndefined; switch (sender.state) { case UIGestureRecognizerStateBegan: { // if (direction == UIPanGestureRecognizerDirectionUndefined) { CGPoint velocity = [sender velocityInView:sender.view]; BOOL isVerticalGesture = fabs(velocity.y) > fabs(velocity.x); if (isVerticalGesture) { if (velocity.y > 0) { direction = UIPanGestureRecognizerDirectionDown; } else { direction = UIPanGestureRecognizerDirectionUp; } } else { if (velocity.x > 0) { direction = UIPanGestureRecognizerDirectionRight; } else { direction = UIPanGestureRecognizerDirectionLeft; } } // } break; } case UIGestureRecognizerStateChanged: { switch (direction) { case UIPanGestureRecognizerDirectionUp: { [self handleUpwardsGesture:sender]; break; } case UIPanGestureRecognizerDirectionDown: { [self handleDownwardsGesture:sender]; break; } case UIPanGestureRecognizerDirectionLeft: { [self handleLeftGesture:sender]; break; } case UIPanGestureRecognizerDirectionRight: { [self handleRightGesture:sender]; break; } default: break; } } default: break; } }

  • (void) handleUpwardsGesture:(UIPanGestureRecognizer *)pan{ NSLog(@"UIPanGestureRecognizerDirectionUp"); }
  • (void) handleDownwardsGesture:(UIPanGestureRecognizer *)pan{ NSLog(@"UIPanGestureRecognizerDirectionDown"); }
  • (void) handleLeftGesture:(UIPanGestureRecognizer *)pan{ NSLog(@"UIPanGestureRecognizerDirectionLeft"); }
  • (void) handleRightGesture:(UIPanGestureRecognizer *)pan{ NSLog(@"UIPanGestureRecognizerDirectionRight"); }
  • (void)viewDidLoad { [super viewDidLoad]; UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self.view addGestureRecognizer:pan]; return;
收藏
0
sina weixin mail 回到顶部