简体   繁体   中英

Animated Expand/Collapse group in horizontal ScrollView (SwiftUI)

I have a simple ForEach showing 5 or 10 Text views according to the expanded flag. everything is wrapped in a horizontal ScrollView because the text can be very long. The animation when expanding the group looks fine, but when collapsing the group there is a small bouncing, the views goes up and down. This does not happen if I remove the ScrollView. Any idea what could cause this bouncing?

struct ContentView: View {
    @State var expanded = false
    let colors: [Color] = [.red, .green, .blue, .orange, .blue, .brown, .cyan, .gray, .indigo, .mint]
    var body: some View {
        VStack {
            ScrollView(.horizontal) {
                VStack(spacing: 20) {
                    ForEach(colors.prefix(upTo: expanded ? 10 : 5), id: \.self) { color in
                        Text(color.description.capitalized)
                    }
                }
            }
            Button("Expand/collapse") {
                expanded.toggle()
            }
            Spacer()
        }.animation(.easeIn(duration: 1))
    }
}

在此处输入图片说明

You need to use value for animation:

struct ContentView: View {
    @State var expanded = false
    let colors: [Color] = [.red, .green, .blue, .orange, .blue, .red, .green, .blue, .orange, .blue]
    var body: some View {
        VStack {
            ScrollView(.horizontal) {
                VStack(spacing: 20) {
                    ForEach(colors.prefix(upTo: expanded ? 10 : 5), id: \.self) { color in
                        Text(color.description.capitalized)
                    }
                }
            }
            Button("Expand/collapse") {
                expanded.toggle()
            }
            Spacer()
        }.animation(.easeIn(duration: 1), value: expanded) // <<: Here!
    }
}

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