Toggle Saturation of VStacks in ScrollView - SwiftUI

Viewed 88

I have a ScrollView that contains an array of VStacks buttons. The VStack data is filled from a data model named ProductModel. I am also passing through an ObservableObject from another view which is here: (NOTE: This data string does change so it isn't always All. Also one of the ProductModels in the ScrollView will match always match the data being passed through).

class selectedApplication: ObservableObject {
      @Published var selectedApplication = "All"
}

What I am trying to do is grey out all the rows that don't match the passed through data string and only keep the VStack that matches, coloured. After that if a different button is pressed then that VStack becomes coloured and all the others turn/stay grey. I have tried doing this via an @State and using a toggle to change the saturation but had no luck. So any direction on how to fix this would be appreciated! Thanks

This is the view with the VStacks:

struct ProductTab5View: View {
    
    @ObservedObject var application: selectedApplication
    @State private var selection: Bool? = true
    var product: ProductModel
    
    var body: some View {
            ScrollView(.horizontal){
                HStack
                    ForEach(product.application, id: \.self) { item in
                            Button(action: {
                                application.selectedApplication = item
                                selection = false
                            }) {
                                VStack{
                                    Image(item)
                                    Text(item)
                                }
                                .saturation(selection ?? true ? 0.0 : 1.0)
                            }
                    }
            }
    }
}
1 Answers

There's no need for an extra @State variable. You can try the following:

struct ProductTab5View: View {
    @ObservedObject var application: selectedApplication
    var product: ProductModel

    var body: some View {
        ScrollView(.horizontal) {
            HStack
            ForEach(product.application, id: \.self) { item in
                Button(action: {
                    application.selectedApplication = item
                }) {
                    VStack {
                        Image(item)
                        Text(item)
                    }
                    .saturation(application.selectedApplication == item ? 1.0 : 0.1)
                }
            }
        }
    }
}
Related