【问题标题】:Save the Starting Location of a UIView in Objective C在 Objective C 中保存 UIView 的起始位置
【发布时间】:2011-11-24 03:17:12
【问题描述】:

因此,我正在尝试保存 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);
        }];
    }
}

【问题讨论】:

  • 你有解决这个问题的方法吗?

标签: objective-c ios uigesturerecognizer uipangesturerecognizer


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试更改此行:

    startPoint = [gestureRecognizer translationInView:self.view];
    

    到这里:

    startPoint = [gestureRecognizer translationInView:view.superview];
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多