marcus
marcus

Reputation: 83

SwiftUI: How to set toggle isOn in a foreach loop

Hi I have a for each loop which goes through a struct with values and in this for each loop I am trying to create a toggle for each and each needs its own isOn parameter so in my struct I have added 'isToggleOn' and set it to true but i am getting the following error: Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

and this view gets called by another view which provides it with the Sandwich struct

And i am not sure what the best way to approach this and any help would be appreciated.

import SwiftUI

struct IngredientView: View {
    var sandwich: Sandwich
    
 var body: some View {
 ForEach(sandwich.ingredients) {  ingredient in
       HStack {
              Text(ingredient.name)
                        
               Toggle("", isOn:  ingredient.isToggleOn)
                     .toggleStyle(CheckboxToggleStyle(style: .square))
                     .foregroundColor(.blue)
       }
     }

}

 

Upvotes: 0

Views: 387

Answers (1)

you could try something like this:

struct IngredientView: View {
    @Binding var sandwich: Sandwich
    
    var body: some View {
        ForEach($sandwich.ingredients) { $ingredient in
            HStack {
                Text(ingredient.name)
                
                Toggle("", isOn: $ingredient.isToggleOn)
                    .toggleStyle(CheckboxToggleStyle(style: .square))
                    .foregroundColor(.blue)
            }
        }
    }
}

With , for example,

struct ContentView: View {
    @State var sandwich = Sandwich()
    
    var body: some View {
        IngredientView(sandwich: $sandwich)
            .onAppear {
                sandwich.ingredients = [
                    Ingredient(isToggleOn: false, name: "ingredient-1"),
                    Ingredient(isToggleOn: true, name: "ingredient-2"),
                    Ingredient(isToggleOn: false, name: "ingredient-3")]
            }
    }
}

assuming something like this:

struct Ingredient: Identifiable, Codable {
    let id = UUID()
    var isToggleOn: Bool = false
    var name: String = ""
}

struct Sandwich: Codable {
    var ingredients: [Ingredient] = []
}

Upvotes: 1

Related Questions