cocoa-touch - 为什么在动画 block 中设置图层 anchorPoint 时我的 View 跳转?

标签 cocoa-touch animation uiview cglayer

我有一个 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/

相关文章:

ios - 阻止将手势传递给 SuperView

iphone - 如何在 UITableViewCell 自动换行中制作文本?

ios - 如何让图像在触摸时改变其 Alpha

javascript - 为什么这个基本的 anime.js 不起作用?

objective-c - 动画 UIView 原点仅在第一次尝试后才有效

javascript - 在幻灯片 JavaScript 方面需要帮助

ios - 实例化 View 框架以使其适合导航栏/标签栏?

ios - 如何将 UICollectionView 作为 subview 添加到 UIView?

ios - 使用 Objective-C/Swift 单例模型,为什么我们要创建一个共享实例而不只是使用类方法?

ios - App结构 : UIView vs. 分页界面中的UIViewController