I would like to have three SwiftUI Toggles and have them so that if one is on, the other two are off.
The old way of doing something like this using UIKit was didSet{}, which is not the correct way with SwiftUI. I don't know if it is neccessary to delve into Combine in order to solve this problem which, on the surface, seems like it should be simple.
import SwiftUI
// Mutually exclusive toggle switches: when one toggle is on, the other two should be off. This is a start, where to go from here?
struct Junk: View {
@State private var isOn1:Bool = true
@State private var isOn2:Bool = false
@State private var isOn3:Bool = false
var body: some View
{
VStack
{
Toggle("T1", isOn: $isOn1)
Toggle("T2", isOn: $isOn2)
Toggle("T3", isOn: $isOn3)
}
}
}
struct Junk_Previews: PreviewProvider
{
static var previews: some View
{
Junk()
}
}
Since I don't know hte challenges of your design, I won't go into wether it is the right approach or not (unless that is your question). However, to achieve what you asked for, you can use an intermediary binding:
struct Junk: View {
@State private var isOn1:Bool = true
@State private var isOn2:Bool = false
@State private var isOn3:Bool = false
var body: some View
{
let on1 = Binding<Bool>(get: { self.isOn1 }, set: { self.isOn1 = $0; self.isOn2 = false; self.isOn3 = false })
let on2 = Binding<Bool>(get: { self.isOn2 }, set: { self.isOn1 = false; self.isOn2 = $0; self.isOn3 = false })
let on3 = Binding<Bool>(get: { self.isOn3 }, set: { self.isOn1 = false; self.isOn2 = false; self.isOn3 = $0 })
return VStack
{
Toggle("T1", isOn: on1)
Toggle("T2", isOn: on2)
Toggle("T3", isOn: on3)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With