我有一个附加到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;
而不是硬编码,但它不会反弹。可能是因为我在拖动时正在更新该值。我并不特别喜欢硬编码值,但我不确定是否有办法解决这个问题。谢谢!
答案 0 :(得分: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;
}
}