Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SwiftUI, how do I make one Toggle change the state of another Toggle?

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()
    }
}
like image 867
e987 Avatar asked Aug 28 '19 20:08

e987


1 Answers

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)
        }
    }
}
like image 50
kontiki Avatar answered Nov 14 '22 13:11

kontiki