I am trying to animate the contents of a list of points. The list is sorted from highest to lowest, so it reorganizes as lower values are higher than the row above. The animation works great by using .animation(.default) on the list, however, it also animates the entire list when I open the view. The whole list floats into place. I would the list to be static, and just the rows move when necessary to reorder
List {
ForEach(players) { player in
Text(player.score)
}
}.animation(.default)
CodePudding user response:
To animate only when something in the State
data changes, use a withAnimation
surrounding the part where you change it rather than the whole list:
import SwiftUI
struct Player: Identifiable {
var id = UUID()
var score: String
}
struct ContentView: View {
@State var players: [Player] = [
.init(score: "2"),
.init(score: "3"),
.init(score: "6"),
.init(score: "1")]
var body: some View {
VStack {
Button("shuffle") {
withAnimation(.easeIn) {
players.shuffle()
}
}
List {
ForEach(players) { player in
Text(player.score)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}