简体   繁体   中英

Swiftui List animation

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)

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()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM