Hi Emmanuel,
From my experience, withAnimation(body: () throws -> Result)
is the best way to get started. As soon as you wrap an action with this, the action will be animated:
import SwiftUI
struct HomeView: View {
@State private var text: String = "Hello, World!"
var body: some View {
VStack {
// Text displayed:
Text(text)
.font(.largeTitle)
.padding()
// Button to trigger animation when text is changed
Button("Animate Text") {
withAnimation {
text = "SwiftUI is awesome!"
}
}
}
}
}
#Preview {
HomeView()
}
There are many good resources to check out for more advanced animations, but I will just point you to a few that are from credible sources:
If you would like to animate SF Symbols, here are some examples from my own projects (slightly modified):
Button {
withAnimation {
timer.toggleTimer()
}
} label: {
ZStack {
Capsule()
.frame(width: 70, height: 40)
.foregroundStyle(Color.blue.opacity(0.3))
Image(systemName: timer.isRunning ? "pause" : "play")
.foregroundStyle(Color.blue)
.font(Font.system(size: 22))
.contentTransition(.symbolEffect(.replace)) //When the timer is toggled to either the pause or play state, the Symbol replacement is animated
}
.buttonStyle(.plain)
As far as rotating, this is a custom rotation effect I created in the CWC+ Project Tracker app. First off, we declare @State private var animationRotation = 0
in our View struct. Then we have a SwiftUI button that is used across two views:
Button(action: {
// Add project update
newUpdate = ProjectUpdate()
}, label: {
ZStack {
Circle()
.foregroundStyle(Color.black)
.frame(width: 65)
Image("Cross")
}
})
.rotationEffect(.degrees(Double(animationRotation)))
When this view appears after navigating from the other view, we run this:
.onAppear {
withAnimation {
animationRotation = 90
}
}
That’s it! The “plus” button rotates 90 degrees when the view appears.
Let me know if you have any more questions. I would be happy to help. I have spent quite a bit of time with different types of animations in building my own apps.
Have a nice day!
-Michael 