Member-only story
Floating Hearts Animation in SwiftUI
How to make Instagram live like button animation in SwiftUI

To make a like button animation similar to Instagram’s, we will use GeometryEffect
and ViewModifier
. You can also use SKScene
and a SpriteView
to achieve similar results.

Heart’s GeometryEffect
First, we need to create a geometry effect that changes the heart’s x and y directions/positions over time. The x positions will be close to each other, centered or off-centered, by a value between -0.05 and 0.05. The y directions will vary using sin and a y value between -pi and 0. If your like button is large, these slight movements might not be enough. Adjust the x and y values as you see fit.
Follow the steps below to return the correct projection transform:
- Add a speed variable and give it a random value between 100 and 200.
- Add a time variable and an animatableData variable of type Double. The animatableData will starts our time and 0 and change it gradually to a given time that we will pass from our ViewModifier that we will create next.
- Create a xTranslation variable that multiplies the x direction and speed.
- Create a yTranslation variable that multiplies the sin of the y direction, speed and time.
- Create and return a CGAffineTransform with our xTranslation and yTranslation.
Tap To Like ViewModifier
In this section, we are creating a ViewModifier
that contains our content. Here, we will change the time value using WithAnimation
, and pass it to our GeometryEffect
modifier.
To make the hearts fade out, add an opacity modifier and give it a 0 when our time is equal to the duration set for the heart animation. See the code below.