Home > Mobile >  Animated Expand/Collapse group in horizontal ScrollView (SwiftUI)
Animated Expand/Collapse group in horizontal ScrollView (SwiftUI)

Time:11-08

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

enter image description here

CodePudding user response:

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!
    }
}
  • Related