To animate padding changes in SwiftUI when the value comes from a published property in a view model, you have a few approaches:
Approach 1: Using .animation() modifier on the view
class ViewModel: ObservableObject {
@Published var padding: CGFloat = 20
func updatePadding() {
padding = padding == 20 ? 50 : 20
}
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
VStack {
Text("Hello, World!")
.padding(viewModel.padding)
.background(Color.blue)
.animation(.easeInOut(duration: 0.5), value: viewModel.padding)
Button("Change Padding") {
viewModel.updatePadding()
}
}
}
}
Approach 2: Using withAnimation() in the view model
class ViewModel: ObservableObject {
@Published var padding: CGFloat = 20
func updatePadding() {
withAnimation(.easeInOut(duration: 0.5)) {
padding = padding == 20 ? 50 : 20
}
}
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
VStack {
Text("Hello, World!")
.padding(viewModel.padding)
.background(Color.blue)
Button("Change Padding") {
viewModel.updatePadding()
}
}
}
}
Approach 3: Using withAnimation() in the view
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
VStack {
Text("Hello, World!")
.padding(viewModel.padding)
.background(Color.blue)
Button("Change Padding") {
withAnimation(.easeInOut(duration: 0.5)) {
viewModel.updatePadding()
}
}
}
}
}
Key Points:
- Approach 1 is often preferred because it keeps the animation logic close to the UI and gives you fine control over which specific properties animate
- Approach 2 centralizes animation logic in the view model, which can be useful if multiple views need the same animation behavior
- Approach 3 gives the view control over when animations occur
The .animation() modifier with a value parameter (Approach 1) is generally recommended for newer SwiftUI versions as it's more explicit about what triggers the animation and avoids unintended animations on other properties.
You can customize the animation by replacing .easeInOut(duration: 0.5) with other options like .spring(), .linear(duration: 1.0), or .easeOut(duration: 0.3).