SwiftUI makes animating your user interface shockingly easy.
Instead of calculating frames and durations manually, you simply tell SwiftUI what state should change, and it automatically interpolates the transition for you.
There are two main ways to animate views in SwiftUI: Explicit animations and Implicit animations.
withAnimation)Explicit animations are triggered by wrapping a state change inside a withAnimation block.
This tells SwiftUI that any views affected by this specific state change should animate to their new values.
import SwiftUIstruct ScaleButton: View { @State private var isScaled = false var body: some View { Button("Press Me") { // The state change is wrapped in withAnimation withAnimation(.spring()) { isScaled.toggle() } } .padding() .background(Color.blue) .foregroundColor(.white) // The scale effect reacts to the animated state change .scaleEffect(isScaled ? 1.5 : 1.0) } }
.animation)Implicit animations are added directly to a view using the .animation() modifier.
This tells the view: "Any time the specified value changes, animate the change."
struct RotateIcon: View {
@State private var degrees = 0.0
var body: some View {
Image(systemName: "arrow.2.circlepath")
.font(.largeTitle)
.rotationEffect(.degrees(degrees))
// The view will automatically animate whenever 'degrees' changes
.animation(.easeInOut(duration: 1.0), value: degrees)
.onTapGesture {
degrees += 180
}
}
}
SwiftUI provides numerous built-in animation curves to make your app feel lively:
.linear: Animates at a constant speed..easeIn: Starts slow, then speeds up..easeOut: Starts fast, then slows down..easeInOut: Slow at the start and end, fast in the middle..spring: Adds a realistic bounce effect to the end of the animation..bouncy: A highly refined, modern spring animation standard in iOS.Animations control how a view changes. Transitions control how a view arrives on screen or leaves the screen.
You can use the .transition(.slide) or .transition(.opacity) modifiers in combination with withAnimation to create beautiful entrance effects!
Which function block do you use to trigger an explicit animation when updating a state variable?