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

10

我是iOS新手,我在我的项目中使用了UIPanGestureRecognizer。 我有一个要求,即在拖动视图时获取当前触摸点和先前触摸点。我正在努力获得这两个点。

如果我使用touchesBegan方法而不是使用UIPanGestureRecognizer,我可以通过以下代码获取这两个点:

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

我需要在UIPanGestureRecognizer事件触发方法中获取这两个点。 我该如何实现? 请指导我。

5个回答

18

你可以使用这个:

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

如果找不到以前的位置,则通过设置当前位置来储存上一个位置,并每次添加当前位置。

previousLocation = [recognizer locationInView:self.view]; 

4
当您将一个 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:的方法。

2

如果你不想存储任何东西,你也可以这样做:

let location = panRecognizer.location(in: self)
let translation = panRecognizer.translation(in: self)
let previousLocation = CGPoint(x: location.x - translation.x, y: location.y - translation.y)

0
您应该按照以下方式实例化您的平移手势识别器:
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
}

0

UITouch中有一个函数可以获取视图中的上一个触摸

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接