Home > Software design >  SwiftUI: Execute Function When Disclosure Group Expands?
SwiftUI: Execute Function When Disclosure Group Expands?

Time:08-04

So when I tap on my discosure group and it expands, I want it to run a function viewModel.postMovie(). How do I get this to work? I tried .onChange(of: expandMovie), if expandMovie == true { }, and switch expandMovie { case true: ...} and none of them still execute in my app. Please help! It's urgent!

Note: expandMovie is declared like this: @State var expandMovie = false

DisclosureGroup(selectedMovie ?? "No Movies Available", isExpanded: $expandMovie) {
    VStack {
        ForEach(viewModel.MoviesModel, id: \.self) { entity in
        Text(entity.movie ?? "Not Available")
        .padding()
        .onTapGesture {
            self.selectedMovie = entity.movie
            withAnimation {
                //viewModel.postMovie()
                self.expandMovie.toggle()
            }
        }
    }
}
.onChange(of: expandMovie) {                                
    viewModel.postMovie(title, genre)
}

CodePudding user response:

Here is a demo on code from referenced (in comment) post - verify a place where you added onChange(of: and make sure each disclosure group has own bound source of truth (otherwise they rather react all at once)

    List {
        ForEach(Array(items.enumerated()), id: \.1.id) { i, group in
            DisclosureGroup(isExpanded: $flags[i]) {
                ForEach(group.items ?? []) { item in
                    Label(item.name, systemImage: item.icon)
                }
            } label: {
                Label(group.name, systemImage: group.icon)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        withAnimation {
                            self.flags[i].toggle()
                        }
                    }
            }
        }
    }
    .onChange(of: flags) { _ in
        print(String(describing: flags))    // << here !!
    }

Tested with Xcode 13.4 / iOS 15.5

  • Related