我现在用的是locationInView设置我布顿的位置,当用户将其释放。 出狱后,我给位置之前储存但事实上,我的按钮不会回到正确的位置。
这是我的代码:
- (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);
给一个错误的效果。 有人知道为什么吗?
一对夫妇的想法:
我建议要确保你捕捉startLocation
你做的任何改变前center
。
您正在使用的用户触摸的位置startLocation
。 你真的应该与初始化这个center
的的recognizer.view
。 这是极不可能的用户正是开始在按钮中心的姿态。 而作为一个结果,你不可能在原来的位置返回回来。
有点风马牛不相及,但是:
你并不需要使用CGMakePoint
复位时center
的recognizer.view
中UIGestureRecognizerStateEnded
条款。 您可以使用CGPointMake
如果你真的想要的,但它是没有必要的。 你可以只用startLocation
,如果你想要的。
你可能会想动画视图返回回到那个startLocation
。 它的不和谐它立刻去那里。
顺便说一句,如果你已经保存startLocation
,你并不需要不断地重置translation
。 只需使用startLocation
加translation
。 似乎更清楚地知道,但显然这是主观的。
我个人认为NSStringFromCGPoint
登录时是非常有用的CGPoint
结构。
所以,我建议:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer
{
static CGPoint startLocation;
if (recognizer.state == UIGestureRecognizerStateBegan)
{
startLocation = recognizer.view.center;
NSLog(@"Began: %@", NSStringFromCGPoint(startLocation));
}
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(startLocation.x + translation.x,
startLocation.y + translation.y);
if (recognizer.state == UIGestureRecognizerStateEnded)
{
NSLog(@"Ended Bef: %@", NSStringFromCGPoint(startLocation));
[UIView animateWithDuration:0.25
animations:^{
recognizer.view.center = startLocation;
}];
CGPoint finalLocation = [recognizer locationInView:self.view];
NSLog(@"Ended Aft: %@", NSStringFromCGPoint(finalLocation));
}
}
我想你应该尝试使用
startLocation = [recognizer locationOfTouch:0 inView:self.view];
代替
startLocation = [recognizer locationInView:self.view];