1

当用户释放它时,我正在使用 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);

给出错误的效果。有人知道为什么吗?

4

1 回答 1

3

几个想法:

  1. 我建议startLocation在对center.

  2. 您正在使用用户触摸的位置startLocation。你真的应该centerrecognizer.view. 用户不太可能在按钮的中心精确地开始他们的手势。因此,您不太可能回到原来的位置。

有点不相关,但是:

  1. CGMakePoint重置子句中的centerof时不需要使用。如果你真的想要,你可以使用,但它是不必要的。如果你愿意,你可以使用。recognizer.viewUIGestureRecognizerStateEndedCGPointMakestartLocation

  2. 您可能希望将视图的返回设置为动画startLocation。让它立即去那里是不和谐的。

  3. 顺便说一句,如果您已保存startLocation,则无需不断重置translation. 只需使用startLocationplus translation。对我来说似乎更清楚,但显然这是主观的。

  4. 我个人认为在记录结构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));
    }
}
于 2013-04-17T21:54:28.007 回答