'Disable button based on checkbox values in SwiftUI

In UI, I should have checkboxes and button. The number of checkboxes is dependent on API. When all checkboxes are checked, the button has to be enabled.

I have viewModels and models like below. This is a high level example. The hierarchy is fixed.

class viewModel: ObservableObject {
@Published var cars : [Cars]
}
class Cars {
@Published var bmw : [Bmw]
}
class Bmw {
@Published var isSelected = false
var carName = ""

init() {
...
}
}

The number of Bmw items is dependent on API. I have created checkbox in SwiftUI like below because the count is dynamic

"made a subview with one checkbox and one @State var, so each checkbox has its "own" state."

Now how do I disable the button based on checkbox value.



Solution 1:[1]

map your data to list of Items like this

struct MyItem {
    var content: String // the info of your data
    var checked: Bool
}

then use it for your view like this

struct CheckAllBoxToApplyButtonView: View {
    @Binding var items: [MyItem]
    var commit: ()->()
    var body: some View {
        VStack {
            // the button that only active when all items are checked
            Button(action: commit) {
                Text("All Checked")
            }
            .disabled(!items.allSatisfy { $0.checked == true })
            
            // checkbox for all items
            ForEach(items.indices, id:\.self) { i in
                Toggle(items[i].content, isOn: $items[i].checked)
            }
        }
    }
}

check out How can I create a text with Checkbox in SwiftUI? if you want your toggle has checkbox UI style

Note: I recommend you to map your data into something like MyItem to separate your Model from your View, your View shouldn't know anything about car or bmw but rather what to display and what to response when user interacts it

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 meomeomeo