3

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)

1 Answer 1

7

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()
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

How do you change the List animation type tho? In UITable you can choose different animation types, like opacity, slide in, slide down, etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.