如何获得在UIPanGestureRecognizer方法当前触摸点和以前的接触点?(How to

2019-08-02 10:51发布

我是新来的iOS,我使用UIPanGestureRecognizer在我的项目。 在我有一个要求得到当前触摸点和之前的触摸点,当我拖着视图。 我挣扎着爬这两点。

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

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

我需要在这两点UIPanGestureRecognizer事件火法。 我怎样才能做到这一点? 请指导我。

Answer 1:

您可以使用此:

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

通过设置当前位置,如果没有找到和添加当前的位置,每次存储以前的位置。

previousLocation = [recognizer locationInView:self.view]; 


Answer 2:

当您将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:



Answer 3:

有一个在UITouch一个函数来获取先前触摸视图

  • (CGPoint)locationInView:(UIView的*)视图;
  • (CGPoint)previousLocationInView:(UIView的*)视图;


Answer 4:

你应该实例化平移手势识别如下:

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
}


Answer 5:

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

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)


文章来源: How to get current touch point and previous touch point in UIPanGestureRecognizer method?