I'm trying to create a view that has two toggles that both operate off the same variable, but the twist is that I want one to be the inverse of the variable and only be toggled on when the variable is false.
At first I looked for a simple way to invert the isOn variable with a well placed exclamation point:
> Toggle(isOn: $myStruct.myBooleanVar) {
Text("Yes").frame(width: 80)
}.toggleStyle(.button)
Toggle(isOn: $myStruct.!myBooleanVar) {
Text("no").frame(width: 80)
}.toggleStyle(.button)
I was unsuccessful
'.!' is not a binary operator
Next I looked to see if there was a modifier I could put on the toggle to invert it. Something like:
> Toggle(isOn: $myStruct.myBooleanVar) {
Text("Yes").frame(width: 80)
}.toggleStyle(.button)
Toggle(isOn: $myStruct.myBooleanVar) {
Text("no").frame(width: 80)
}.toggleStyle(.button)
.inverted(true)
I found no such modifier
Next I tried using procedural variables, state variables, and custom binding variables, but they all gave the same error:
Cannot use instance member 'settings' within property initializer; property initializers run before 'self' is available
CodePudding user response:
you could try this approach to have ...two toggles that both operate off the same variable, but the twist is that I want one to be the inverse of the variable and only be toggled on when the variable is false.
:
Toggle(isOn: $myBooleanVar) {
Text("Yes").frame(width: 80)
}
Toggle(isOn: Binding(
get: { !myBooleanVar },
set: { if !$0 { myBooleanVar = !$0 } } )) { // <-- more logic if required
Text("no").frame(width: 80)
}