简体   繁体   中英

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.

I want to move the UIView in an animation block, but have the sub-views not move with the parent. If the view was to move 50 points to the right, more of the second image would be seen, and less of the first.

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. 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.

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

QuartzCore.framework

Cheers,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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