9

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

如果我使用touchesBeganmethod 而不是 using UIPanGestureRecognizer,我可以通过以下代码得到这两点:

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

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

4

5 回答 5

17

你可以使用这个:

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

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

previousLocation = [recognizer locationInView:self.view]; 
于 2012-11-07T13:08:06.477 回答
4

当您将 an 链接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:.

于 2012-11-07T13:08:43.853 回答
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)
于 2019-03-15T16:08:12.250 回答
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
}
于 2012-11-07T13:10:06.450 回答
0

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

  • (CGPoint)locationInView:(UIView *)view;
  • (CGPoint)previousLocationInView:(UIView *)view;
于 2014-12-26T09:12:57.680 回答