我是新来的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];
通过设置当前位置,如果没有找到和添加当前的位置,每次存储以前的位置。
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:
你应该实例化平移手势识别如下:
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
}
如果您不想存储任何你也可以这样做:
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?