我有一个 UIPanGestureRecognizer 附加到我的 iOS 应用程序中的视图。我从以下位置复制了代码触摸示例应用程序 https://developer.apple.com/library/ios/samplecode/Touches/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007435对于平底锅处理程序。当手势开始时,我的代码:
- 记录原始锚点和中心。
-
将锚点和中心更改为用户手指周围,如下所示:
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;
随着手势的进行,平移处理程序会不断改变中心以跟踪手指的移动。到目前为止,一切都很好。
当用户放开时,我希望视图以动画方式返回到其原始起点。执行此操作的代码如下所示:
[UIView animateWithDuration:2 delay:0 options:UIViewAnimationCurveEaseOut animations:^{
target.center = originalCenter;
target.layer.anchorPoint = originalAnchorPoint;
}];
这确实使视图回到原来的起点。但是,在动画开始之前,视图会跳转到 UI 中的不同位置。 IOW,放开它,它会跳起来,然后它会动画回到它所属的地方。
我想也许我需要在动画之外设置锚点和中心,也许将中心设置为超级视图中的位置,就像手势开始时一样,但这似乎没有什么区别。
我在这里缺少什么?如何防止用户放开时跳转?
我怀疑有两个问题没有尝试你正在做的事情:
更改锚点会更改视图/图层的位置。为了在不修改位置的情况下更改锚点,您可以使用像这样的一些助手:
-(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;
}
(我自己在我的项目中使用它。在这里找到:更改 CALayer 的锚点会移动视图 https://stackoverflow.com/questions/1968017/changing-my-calayers-anchorpoint-moves-the-view)
您的动画将锚点设置回其原始值。您应该使用上面的助手来重置锚点。这可以确保更改锚点时视图不会移动。你必须这样做动画之外。然后,使用动画块更改视图的中心并将其动画到您想要的位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)