In SwiftUI, if I add a Button to a List, the List no longer animates when the collection changes. How can I make it animate?
Here's a reproduction. In the code's current form, animation works when the list is shuffled. However, if I replace Text
with Button
, the list no longer animates when I tap Shuffle.
struct ContentView: View {
@State private var fruits = ["apple", "banana", "cherry"]
var body: some View {
NavigationStack {
List(fruits, id: \.self) { fruit in
Text(fruit)
// Button(fruit) {} // Uncomment this line and comment the line above to reproduce the problem.
}
.toolbar {
Button("Shuffle") {
withAnimation { fruits = fruits.shuffled() }
}
}
}
}
}
The default button style within a List has some built-in behaviors that affect animations and interaction.
You should add the modifier .buttonStyle(.plain) to fix it
struct ContentView: View {
@State private var fruits = ["apple", "banana", "cherry"]
var body: some View {
NavigationStack {
List {
ForEach(fruits, id: \.self) { fruit in
Button(action: {}) {
Text(fruit)
.frame(maxWidth: .infinity, alignment: .leading)
}
.buttonStyle(.plain)
}
}
.toolbar {
Button("Shuffle") {
withAnimation {
fruits.shuffle()
}
}
}
}
}
}