I have some Toggle Switches in a row but I want to prevent switches ON if already two of them is ON. And showing an Alert that maximum 2 of them is allowed to ON. Here is my code:
struct PreventToggle: View {
@State private var isCheckeds = [false, true, true, false, false, false]
@State var showAlert = false
var body: some View {
let numberOfTrue = isCheckeds.filter{$0}.count
showAlert = numberOfTrue > 2
return ForEach(0 ..< isCheckeds.count) { id in
Toggle("Switch \(id)", isOn: self.$isCheckeds[id])
.alert(isPresented: self.$showAlert) {
Alert(title: Text("Maximum Limit!"), message: Text("Maximum limit is: 3"), dismissButton: .default(Text("Got it")))
}
}
}
}
