简体   繁体   中英

How to create an inverted Toggle in SwiftUI?

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

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM