如何在UIPanGestureRecognizer方法中获取当前触点和上一个触点?

我是新来的iOS,我在我的项目中使用UIPanGestureRecognizer 。 我在拖动视图时需要获取当前触摸点和上一个触摸点。 我正在努力得到这两点。

如果我使用touchesBegan方法而不是使用UIPanGestureRecognizer ,我可以通过下面的代码得到这两点:

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint touchPoint = [[touches anyObject] locationInView:self]; CGPoint previous=[[touches anyObject]previousLocationInView:self]; } 

我需要在UIPanGestureRecognizer事件触发方法中获得这两点。 我怎样才能做到这一点? 请指导我。

你可以使用这个:

 CGPoint currentlocation = [recognizer locationInView:self.view]; 

通过设置当前位置存储以前的位置,如果没有find,并且每次添加当前位置。

 previousLocation = [recognizer locationInView:self.view]; 

UIPanGestureRecognizer链接到IBAction时,每次更改都会调用该操作。 手势识别器还提供一个称为state的属性,指示它是第一个UIGestureRecognizerStateBegan ,最后一个UIGestureRecognizerStateEnded还是仅仅是UIGestureRecognizerStateChanged之间的一个事件。

要解决您的问题,请尝试如下:

 - (IBAction)panGestureMoveAround:(UIPanGestureRecognizer *)gesture { if ([gesture state] == UIGestureRecognizerStateBegan) { myVarToStoreTheBeganPosition = [gesture locationInView:self.view]; } else if ([gesture state] == UIGestureRecognizerStateEnded) { CGPoint myNewPositionAtTheEnd = [gesture locationInView:self.view]; // and now handle it ;) } } 

你也可以看一下名为translationInView:的方法。

在UITouch中有一个function来获取视图中的上一个触摸

  • (CGPoint)locationInView:(UIView *)view;
  • (CGPoint)previousLocationInView:(UIView *)view;

你应该实例化你的平移手势识别器,如下所示:

 UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; 

那么你应该添加panRecognizer到你的视图:

 [aView addGestureRecognizer:panRecognizer]; 

当用户与视图交互时,将调用- (void)handlePan:(UIPanGestureRecognizer *)recognizer方法。 在handlePan中:你可以像这样触及点:

 CGPoint point = [recognizer locationInView:aView]; 

你也可以得到panRecognizer的状态:

 if (recognizer.state == UIGestureRecognizerStateBegan) { //do something } else if (recognizer.state == UIGestureRecognizerStateEnded) { //do something else }