SwiftUI | Some examples of modern animations with demo cafe app
This time I brought an example project using
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 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.
matchedGeometryEffect isn’t difficult. All we have to consider is just matching
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
ids. That’s why I made my
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
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.
You may be familiar with
DispatchQueue. The role of
DispatchQueue and two variables(
show2) is helping us to run animations with different delays. You can adjust those delays easily by changing the
DispatchQueue and run more animations by adding more
DispatchQueue & variable pairs.
3. matchedGeometryEffect again
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
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!