我有一个 UIPanGestureRecognizer 附加到我的 iOS 应用程序中的 View 。我从 Touches sample app 复制了代码对于平底锅处理程序。当手势开始时,我的代码:
- 记录原始 anchor 和中心。
将 anchor 和中心更改为围绕用户的手指,如下所示:
CGPoint locationInView = [gestureRecognizer locationInView:target]; CGPoint locationInSuperview = [gestureRecognizer locationInView:target.superview]; target.layer.anchorPoint = CGPointMake( locationInView.x / target.bounds.size.width, locationInView.y / target.bounds.size.height ); target.center = locationInSuperview;
随着手势的进行,平移处理器不断改变中心以跟踪手指的移动。到目前为止一切顺利。
当用户松开时,我希望 View 以动画方式回到其原始起点。执行此操作的代码如下所示:
[UIView animateWithDuration:2 delay:0 options:UIViewAnimationCurveEaseOut animations:^{
target.center = originalCenter;
target.layer.anchorPoint = originalAnchorPoint;
}];
这确实使 View 动画回到其原始起点。但是,在动画开始之前, View 会跳转到 UI 中的不同位置。 IOW,放手,它会跳跃,然后它会动画回到它所属的位置。
我想也许我需要在动画之外设置 anchor 和中心,也许将中心设置到 super View 中的位置,就像手势开始时一样,但这似乎没有什么区别。
我在这里错过了什么?如何在用户松开时防止跳转?
最佳答案
我怀疑有两个问题没有尝试你在做什么:
更改 anchor 会更改 View /层的位置。为了在不修改位置的情况下更改 anchor ,您可以使用像这样的帮助程序:
-(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view
{
CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y);
CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
CGPoint position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = anchorPoint;
}
(我自己在我的项目中使用它。在这里找到:Changing my CALayer's anchorPoint moves the view)
您的动画将 anchor 设置回其原始值。 您应该使用上面的帮助程序来重置 anchor 。这确保了 View 在更改 anchor 时不会移动。您必须在动画之外执行此操作。然后,使用动画 block 更改 View 的中心并将其动画化到您想要的位置。
关于cocoa-touch - 为什么在动画 block 中设置图层 anchorPoint 时我的 View 跳转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468233/