简体   繁体   English

如何移动UIView,但相对于Superview保持其内容位置不变?

[英]How can I move a UIView, but leave its content positions unchanged relative to the superview?

A UIView has 2 images as sub-views, and clip to bounds set to yes. 一个UIView有2个图像作为子视图,并且剪辑范围设置为yes。

I want to move the UIView in an animation block, but have the sub-views not move with the parent. 我想在动画块中移动UIView,但是使子视图不能与父视图一起移动。 If the view was to move 50 points to the right, more of the second image would be seen, and less of the first. 如果视图是向右移动50个点,则将看到更多的第二张图像,而看不到第一张图像。

I can move the view manually, and update the subview positions opposite the new view position, but I can't figure out how to achieve the same thing in a block. 我可以手动移动视图,并更新与新视图位置相对的子视图位置,但是我无法弄清楚如何在一个块中实现相同的目的。

I think the limitation you're running into has to do with the fact that UIView Animation blocks use Core Animation under the hood, and Core Animation animates a 'presentation' layer which is a copy of the original view/layer that the animation was scheduled on. 我认为您遇到的限制与以下事实有关:UIView Animation块在后台使用Core Animation,而Core Animation设置了一个“表示”层的动画,该层是已安排动画的原始视图/层的副本上。 So during your block's animation, the presentation layer's position is changing, but the position of the model view remains unchanged. 因此,在块的动画期间,表示层的位置会发生变化,但是模型视图的位置保持不变。

Since you mentioned that you can update the view position manually (and subview positions in the opposite direction) to achieve the desired effect, consider creating an NSTimer at animation schedule time that runs 60 times per second (to try and catch every animation frame) that simply queries the presentation layer for its current position (as set by the animation itself + any special timing functions specified as argument to the animation), and perform your work to update the underlying model to match that. 由于您提到可以手动更新视图位置(和相反方向的子视图位置)以获得所需的效果,因此请考虑在动画调度时间创建一个NSTimer,该时间每秒运行60次(以尝试捕获每个动画帧),只需查询表示层的当前位置(由动画本身+指定为动画参数的任何特殊计时功能设置),然后执行工作以更新基础模型以匹配该位置。

You should be able to query the animated layer's position with: 您应该能够通过以下方式查询动画层的位置:

yourUIView.layer.presentationLayer.frame.origin

Then add a completion block to your animation that invalidates the timer. 然后,将完成块添加到动画中,使计时器无效。

Before you can access the view's layer property, you must add to your project the 在访问视图的layer属性之前,必须将

QuartzCore.framework

Cheers, 干杯,

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

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