Yann Morin Charbonneau
Yann Morin Charbonneau

Reputation: 177

SwiftUI Toggle Switch without Binding

This may seem like an odd question but I have looked around and can't seem to find an answer for it.

I would like to create toggles in a view that are not binded to any variable. Imagine a list of toggle switches that are toggle-able but don't actually do anything.

I have tried using .constant butt as you would expect, that doesn't allow me to toggle the switch. Obviously leaving It blank throws an error.

//Can't be changed
Toggle(isOn: .constant(true)) {
       Text("Checkbox")
}

//Throws an error
Toggle() {
       Text("Checkbox")
}

Is there anything that can be passed in the isOn: parameter to allow for that?

Edit:

In theory I could just have a @State variable in my view and binding to the toggle and simple not used that variable anywhere else in my view. Only thing is, I do not know ahead of time how many toggles will be displayed in my view so I can't just declare a bunch of @State variables. And if I were too only create one @State variable and blind it to all of my toggles, they would all be in sync, which is not what I am looking for, I would like them to all be independent.

Below is a simplified example of the layout of my view

private var array: [String]
var body: some View {
    ForEach((0..<self.array.count), id: \.self) {
        Toggle("Show welcome message", isOn: *binding here*)
    }
}

Thank you

Upvotes: 4

Views: 2154

Answers (1)

George
George

Reputation: 30341

You can simply create a single @State variable of type [Bool], an array containing all the toggle booleans.

Here is some example code:

struct ContentView: View {
    
    var body: some View {
        ToggleStack(count: 5)
    }
}

struct ToggleStack: View {
    @State private var toggles: [Bool]
    private let count: Int
    
    init(count: Int) {
        self.count = count
        toggles = Array(repeating: true, count: count)
    }
    
    var body: some View {
        VStack {
            ForEach(0 ..< count) { index in
                Toggle(isOn: $toggles[index]) {
                    Text("Checkbox")
                }
            }
        }
    }
}

Result:

Result

Upvotes: 2

Related Questions