简体   繁体   中英

How to animate removal transition of multiple rows from SwiftUI List?

Please see this sample view that demonstrates the problem:

struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
                    .transition(AnyTransition.opacity.animation(.default))
            }
        }
        .padding()
    }
}

struct ListRemovalTransition_Previews: PreviewProvider {
    static var previews: some View {
        ListRemovalTransition()
    }
}

过渡演示

The desired outcome is that the individual rows fade out when removed without changing position. Instead what's happening seems like all the rows first overlap each other before being removed. I've added a transition with animation to the row Text but this has no impact.

Just add id(:) modifier to List to remove default animation. Then add transition(:) modifier to List for your desirable transition. It works perfectly. I just tested on Xcode 11.5. Here is my code...

struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
            }
            .id(UUID())
            .transition(AnyTransition.opacity.animation(.default))
        }
        .padding()
    }
}

https://media.giphy.com/media/dVu1CMqk3YdtZHefaE/giphy.gif

Thanks. X_X

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