'Disclosure group open/close animation

I'm trying to animate the opening and closing of a disclosure group. I've tried several attempts without being able to get any sort of animation.

This code synthesizes what I'm trying to do in a more complicated app.

class Sample: ObservableObject, Identifiable {
  let uuid = UUID()
  let title: String
  let data: [String]
  
  @Published var isExpanded = false
  
  init(title: String, data: [String]) {
    self.title = title
    self.data = data
  }
}

class TopModel: ObservableObject {
  var models = [Sample(title: "Sample1", data: ["1", "2", "3", "4", "5", "6"]),
                Sample(title: "Sample2", data: ["1", "2", "3", "4", "5", "6"]),
                Sample(title: "Sample3", data: ["1", "2", "3", "4", "5", "6"])]
}

@main
struct TestDisclosureApp: App {
  @StateObject var topModel = TopModel()
  
  var body: some Scene {
    WindowGroup {
      ContentView()
        .environmentObject(topModel)
    }
  }
}

struct ContentView: View {
  @EnvironmentObject var topModel: TopModel
  
  var body: some View {
    NavigationView {
      List {
        ForEach($topModel.models) { $model in
          RowView(model: $model)
        }
      }
    }
  }
}

struct RowView: View {
  @Binding var model: Sample
  
  var body: some View {
    
    VStack {
      DisclosureGroup("Group: \(model.title)", isExpanded: $model.isExpanded) {
        ForEach(model.data, id:\.self) { data in
          Text(model.title)
          Text(data)
        }
      }
      .onTapGesture {
        withAnimation {
          model.isExpanded.toggle()
        }
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

The disclosure group is in RowView and presently setup to toggle with a tapGesture. How can get the opening and closing to animate? Someone, pease enlighten me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source