繁体   English   中英

使用摇动手势重置UIView的框架而无需对开始值进行硬编码

[英]Reset UIView's frame with a pan gesture without hardcoding start values

我有一个附加到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; 

而不是硬编码,但不会返回。 可能是因为我在拖动时正在更新该值。 我不特别喜欢对值进行硬编码,但是我不确定是否有解决方法。 谢谢!

您实际上只需要跟踪视图的原始中心。 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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM