2

我有一个附加到 UIView 的 UIPanGestureRecognizer。我想要做的基本上是拖放到一个桶中。如果用户放开 UIView 并且它不在存储桶中,我希望它动画回到原来的起始位置。为我的 UIPanGestureRecognizer 调用的选择器是:

- (void)handleDragDescriptionView:(UIPanGestureRecognizer *)gestureRecognizer {
    UIView *panViewPiece = [gestureRecognizer view];
    CGRect originalFrame = CGRectMake(946, 20, 58, 30);

    CGPoint translation = [gestureRecognizer translationInView:panViewPiece];
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan || gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        panViewPiece.center = CGPointMake(panViewPiece.center.x + translation.x, panViewPiece.center.y + translation.y);

        [gestureRecognizer setTranslation:CGPointZero inView:panViewPiece.superview];
    }
    else if (gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
        [UIView animateWithDuration:0.25 animations:^{
            self.dragDescriptionView.frame = originalFrame;
        }];
    }
    else {
        [UIView animateWithDuration:0.25 animations:^{
            self.dragDescriptionView.frame = originalFrame;
        }];
    }

}

我想知道我是否可以在没有originalFrame方法顶部的情况下做到这一点。我原本有

CGRect originalFrame = _dragDescriptionView.frame; 

而不是硬编码,但它不会快速恢复。可能是因为我在拖动时更新了该值。我不是特别喜欢硬编码值,但我不确定是否有办法解决这个问题。谢谢!

4

1 回答 1

5

您实际上只需要跟踪视图的原始中心。创建一个实例变量并仅在originalCenter手势开始时设置它:

@implementation MyViewController {
    CGPoint _originalCenter;
}

- (void)handleDragDescriptionView:(UIPanGestureRecognizer *)gestureRecognizer {
    UIView *panViewPiece = [gestureRecognizer view];

    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            _originalCenter = panViewPiece.center;
            break;

        case UIGestureRecognizerStateChanged: {
            CGPoint translation = [gestureRecognizer translationInView:panViewPiece.superview];
            panViewPiece.center = CGPointMake(panViewPiece.center.x + translation.x, panViewPiece.center.y + translation.y);
            [gestureRecognizer setTranslation:CGPointZero inView:panViewPiece.superview];
            break;
        }

        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled: {
            [UIView animateWithDuration:0.25 animations:^{
                panViewPiece.center = _originalCenter;
            }];
            break;
        }

        default:
            break;
    }
}
于 2012-11-12T23:39:09.657 回答