This time I brought an example project using matchedGeometryEffect
and DispatchQueue
to implement some fascinating animations. I will show you a simple cafe app which introduces their products.
Let’s peek into a final view.
What are we going to use?
As I mentioned briefly before, two key functions we are going to use are matchedGeometryEffect
and DispatchQueue
. matchedGeometryEffect
makes hero animation available in SwiftUI and DispatchQueue
is used to delay the start of the animation. By mixing those, we will be able to make what we intended.
1. matchedGeometryEffect
Actually, matchedGeometryEffect
isn’t difficult. All we have to consider is just matching namespace
and id
between the objects we want to animate. However, even it doesn’t seem that tricky, there are a few things you should take care of .
First, you have to check the order of modifiers. When matchedGeometryEffect
goes below of some modifiers, especially the frame
, it won’t act as you expected like this case.
Second, you should make sure you are not using duplicate id
s. That’s why I made my Product
struct Identifiable
and gave them an unique ID. If you are using same ID everywhere, it will occur unexpected behavior.
To add some detail explanations about the codes, if you want to share your namespace
with other views, just add var yourNamespace: Namespace.ID
like I did in line 76. Also, there’s a problem that if I used if-else
statement, the position of ScrollView
is initiated. So I used .opacity
rather than if-else
.
So far, we have created a transition animation between product and detail view using matchedGeometryEffect
. Now, let’s add more animations that help to make our views more sophisticated.
2. DispatchQueue
You may be familiar with DispatchQueue
. The role of DispatchQueue
and two variables(show1
, show2
) is helping us to run animations with different delays. You can adjust those delays easily by changing the deadline
in DispatchQueue
and run more animations by adding more DispatchQueue
& variable pairs.
3. matchedGeometryEffect again
It’s matchedGeometryEffect
again. I simply added matchedGeometryEffect
, conditional statements and onTapGesture
. That’s all.
4. Add some details
Difficult things are over. All that’s left is to do this and that for good looking such as Image
and Text
. Then will be able to build an app I introduced at the beginning of this post. I think you guys can understand even I don’t explain it. I will attach the full codes below. Please take a look to check what I did. Thank you for reading!