我是iOS新手,我在项目中使用UIPanGestureRecognizer
。我在拖动视图时需要获取当前触摸点和上一个触摸点。我很难得到这两点。
如果我使用touchesBegan
方法而不是使用UIPanGestureRecognizer
,我可以通过以下代码获得这两点:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchPoint = [[touches anyObject] locationInView:self];
CGPoint previous=[[touches anyObject]previousLocationInView:self];
}
我需要在UIPanGestureRecognizer
事件触发方法中获得这两点。我怎样才能做到这一点?请指导我。
答案 0 :(得分:17)
您可以使用:
CGPoint currentlocation = [recognizer locationInView:self.view];
通过设置当前位置(如果未找到)并每次添加当前位置来存储先前位置。
previousLocation = [recognizer locationInView:self.view];
答案 1 :(得分: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 :(得分: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
}
答案 3 :(得分:0)
UITouch中有一个功能可以在视图中进行上一次触摸
答案 4 :(得分:0)
如果您不想存储任何东西,也可以这样做:
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)