Animate a UIView frame with CALayer as a preview

What I have:

I have UIView's and CAGradientLayer hierarchies that I use to set the "background color" of this hierarchy. So I have something like this:

ViewA β†’ ViewB β†’ CAGradientLayer

What am I doing:

At some point, I want to animate the frame (only its height) in ViewA. So it would be something like this:

 [UIView animateWithDuration:timeInterval delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ viewA.frame = newFrame; }]; 

Problem:

The problem is that the CAGradientLayer will not animate its frame, it will just change its frame, and then viewA will start the animation as intended (this is clearly seen if you set the simulator to slow motion animation).

What I tried:

I tried to do what Apple recommends here by executing it inside the UIView animation UIView , but it actually doesn't work, because I'm still animating the frame here:

 viewA.frame = newFrame; 

I also understand that I have to animate the borders, not the CALayer frame, the problem is that how can I animate the borders and when does the ViewA frame animation leave the CALayer from the animation?

What I want:

I just want to animate the change in its height, so I would simultaneously see the viewA and CAGradientLayer .

+4
source share
2 answers

First of all, read this .

Try encapsulating view animation code with layer animation explicitly. Do not expect the layer to automatically update. Since you are dealing with positioning, you will need to modify graidentlayer.bounds .

If this does not work, try to do this before your animation code:

 [CATransaction begin]; [CATransaction setDisableActions: NO]; [CATransaction commit]; 
+2
source

You need to understand that the hierarchy of UIView and CALayer is different. Layout and animation changes that work with UIView will not automatically affect the CALayer hierarchy.

So, if you want the changes applied to your view to affect the level that you have to update yourself.

Your code is also missing data. For example, you claim to see that your gradient layer has changed it, but you are not showing where you change it. Have you overwritten layoutSubviews somewhere to update its frame ?

By default, updating the frame layer will result in its implicit animation for the position and bounds properties. To change the animation speed, you can use:

 [CATransaction begin]; [CATransaction setAnimationDuration:10.0]; _myLayer.frame = newFrame; [CATransaction commit]; 
+2
source

Source: https://habr.com/ru/post/1494269/


All Articles