How to animate UIView with scale and layer position.
Sooner or later an iOS developer needs custom animations between views. This is often a mixture of position changes and scaling mainly just a view’s frame to another view’s frame animation. You might first try something like this:
Sometimes this will work, but not if
myView has any subviews. For example, if
myView has a label inside, then the frame of the superview will change but the label will stay as is. Instead, we need the label to scale along with the superview. We could apply the frame animation to the label’s frame, but while this changes the size of the label, the font doesn’t scale. We need a better approach. I’ll show you how to use the view’s
transform property and layer’s
position to achieve the goal.
Position and anchor point
In iOS each UIView has a layer with two interesting properties, for our purposes:
position. These two properties are connected and changing an
anchorPoint or the
position of the layer will change its placement in the parent view.
position property is the position of the
anchorPoint in the superview, so changing the
anchorPoint or the
position will affect the placement of the child view in its container superview. The
position value represents points on screen, so setting the x = 1 will move the view by one point to the right. The
anchorPoint value is different. For
anchorPoint, setting x = 1 will set the anchorPoint at the right edge of the view, while x = 0 will set it to the left edge.
Let’s get to animations
Let’s clarify all this with some animations. Start with a view and subview:
Let’s have the initial square animate its frame from
Let’s break this down and start with just the position, so that the smallSquare ends up centered inside the container.
Ok that was easy. Let’s now scale the smallSquare to twice its size while it’s moving to the center.
Great, it looks good. We can now use this as a base for creating a new function that will move the view from its initial frame to a new one.
Now we can write our above transitions as
Now for the anchorPoint
We’ve assumed that the anchorPoint is always set to x: 0.5 and y: 0.5. This is the default position, but someone could have moved the anchorPoint to a different position and we need to takes this into account. We need to change our function from
Now regardless of the anchorPoint’s position, the views will move and scale correctly. For the purpose of scaling and position changes we don’t need to move the anchorPoint of a layer, we can simply rely on
transform to achieve the effect of animation originating from any point in the view.
The method I created may make your life a little easier and your app a little slicker. Below is the full function as an extension to UIView. I will also attach a playground file so you can experiment.
Originally published at blog.montrosesoftware.com on August 21, 2017.