0

因此,我正在尝试保存 UIView 的起始位置,以便我创建的块可以/将在未放置在正确位置时快速返回到该位置。我创建了一个名为“startPoint”的 CGPoint,我想将其坐标设置为块的起点。现在发生的事情是我得到了块,当我释放它时,它会转到屏幕上的 0,0 坐标(左上角)。不完全确定我错过了什么。任何帮助,将不胜感激。下面是手势识别器的代码。

- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer {
    UIView *view = [gestureRecognizer view];
    CGPoint startPoint;


    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        view.backgroundColor = [UIColor redColor];
        startPoint = [gestureRecognizer translationInView:self.view];
    }

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {

        CGPoint translation = [gestureRecognizer translationInView:view.superview];

        view.center = CGPointMake(view.center.x+translation.x, view.center.y+translation.y);

        [gestureRecognizer setTranslation:CGPointZero inView:view.superview];

    } else if ([gestureRecognizer state] == UIGestureRecognizerStateEnded) {

//        double snapX = round(view.center.x / 110) * 110;
//        double snapY = round(view.center.y / 110) * 110;

        double snapX = round(startPoint.x);
        double snapY = round(startPoint.y);

        view.backgroundColor = [UIColor blueColor];

        [UIView animateWithDuration:0.3 animations:^{
            view.center = CGPointMake(snapX, snapY);
        }];
    }
}
4

2 回答 2

1

你有一个名为startPoint. 这意味着pan:每次pan:调用 ( ) 时都会重新创建变量。您需要创建startPoint一个实例变量或属性,以便它被创建一次并在对pan:.

于 2011-11-24T05:50:48.090 回答
0

尝试更改此行:

startPoint = [gestureRecognizer translationInView:self.view];

对此:

startPoint = [gestureRecognizer translationInView:view.superview];

另外,我不确定我是否真的能从您的描述中理解发生了什么,但听起来您应该在startPoint此方法的范围之外声明。

于 2011-11-24T03:24:51.000 回答