I just completed day 32 of 100 days of SwiftUI. Today, I learnt about animations in SwiftUI.
Since SwiftUI is a state-driven UI framework, SwiftUI animates the changes between the state of views.
There are two categories of animations in SwiftUi: Implicit and explicit animations.
Implicit animations are done using the animations modifier. They are used to animate views based on changes in state property.
struct ContentView: View {
@State private var animationAmount: CGFloat = 1
var body: some View {
Button("Tap Me") {
self.animationAmount += 1
}
.scaleEffect(animationAmount)
.animation(.default)
}
}
}
The code above makes a button bigger whenever a user taps. It also animates the transition with the animation modifier. As you can see we don't explicitly say when to start or stop the animation. Everything is handled by SwiftUI.
Explicit animations give you more control over what changes you want to animate. You can do this using withAnimation
closure.
struct ContentView: View {
@State private var opacity = 1.0
var body: some View {
Button("Press here") {
withAnimation {
opacity -= 0.2
}
}
.padding()
.opacity(opacity)
}
}
Top comments (0)