当用户释放它时,我使用locationInView来设置我的bouton的位置。发布后,我给出了之前存储的位置,但事实上,我的按钮没有回到正确的位置。
这是我的代码:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
static CGPoint startLocation;
if (recognizer.state == UIGestureRecognizerStateBegan) {
startLocation = [recognizer locationInView:self.view];
NSLog(@"Began: %d" @"-" @"%d", (int)startLocation.x , (int)startLocation.y);
}
if (recognizer.state == UIGestureRecognizerStateEnded)
{
NSLog(@"Ended Bef: %d" @"-" @"%d", (int)startLocation.x, (int)startLocation.y);
recognizer.view.center = CGPointMake(startLocation.x, startLocation.y);
startLocation = [recognizer locationInView:self.view];
NSLog(@"Ended Aft: %d" @"-" @"%d", (int)startLocation.x, (int)startLocation.y);
}
}
事实上,指示:
recognizer.view.center = CGPointMake(startLocation.x, startLocation.y);
给出错误的效果。有人知道为什么吗?
答案 0 :(得分:3)
有几点想法:
我建议您在更改startLocation
之前确保抓取center
。
您正在使用用户触摸startLocation
的位置。您真的应该使用center
的{{1}}对其进行初始化。用户极不可能在按钮的中心准确地开始他们的手势。因此,您不太可能在原始位置返回。
有点无关,但是:
重置recognizer.view
子句中CGMakePoint
的{{1}}时,您无需使用center
。如果你真的想要,你可以使用recognizer.view
,但这是不必要的。如果需要,您可以使用UIGestureRecognizerStateEnded
。
您可能希望动画将视图返回给CGPointMake
。让它立刻去那里很不利。
另外,如果您保存了startLocation
,则无需不断重置startLocation
。只需使用startLocation
加translation
即可。对我来说似乎更清楚,但显然这是主观的。
我个人认为startLocation
在记录translation
结构时非常有用。
所以,我建议:
NSStringFromCGPoint
答案 1 :(得分:-1)
我认为你应该尝试使用
startLocation = [recognizer locationOfTouch:0 inView:self.view];
而不是
startLocation = [recognizer locationInView:self.view];