SwiftUI Three Toggles that dissable eachother

Hello! I was wondering how you would have three SwiftUI toggles where only one could be on at a time (and one has to be on at all times) so when another one is selected, the others aren't. I really appreciate the help! Thanks.

Answered by BabyJ in 724961022

Something like this will work:

@State private var selectedToggle = 1

var body: some View {
    VStack {
        ForEach(1...3, id: \.self) { num in
            Toggle("Toggle \(num)", isOn: toggleBinding(for: num))
        }
    }
}

func toggleBinding(for num: Int) -> Binding<Bool> {
    Binding {
        num == selectedToggle
    } set: { _ in
        selectedToggle = num
    }
}

You can adjust this to suit your needs.

Accepted Answer

Something like this will work:

@State private var selectedToggle = 1

var body: some View {
    VStack {
        ForEach(1...3, id: \.self) { num in
            Toggle("Toggle \(num)", isOn: toggleBinding(for: num))
        }
    }
}

func toggleBinding(for num: Int) -> Binding<Bool> {
    Binding {
        num == selectedToggle
    } set: { _ in
        selectedToggle = num
    }
}

You can adjust this to suit your needs.

SwiftUI Three Toggles that dissable eachother
 
 
Q