How do I set a group of toggles to be mutually exclusive in swift

青春壹個敷衍的年華 提交于 2020-11-25 03:58:34

问题


@State private var isOn1 = false
@State private var isOn2 = false

var body: some View {
    ScrollView{
        Toggle("switch1",isOn:$isOn1)
        Toggle("switch2",isOn:$isOn2)
    }

Here is what I have so far. Is there a way for me to add an if statement when activating a toggle that all the other toggles will be off. Or is there anyway to change the states of the toggles when activating one. Any answers are appreciated thank you!


回答1:


You can define isOn2 as a Binding. You can create a Binding by passing in a closure for its getter and another one for its setter. For your isOn2 Binding you'll simply need to return the negated value of isOn1 and in its setter, you'll set isOn1 to the negated value passed in to the setter.

struct ToggleView: View {
    @State private var isOn1 = false

    var body: some View {
        let isOn2 = Binding<Bool>(
            get: { !self.isOn1 },
            set: { self.isOn1 = !$0 }
        )
        return ScrollView{
            Toggle("switch1",isOn: $isOn1)
            Toggle("switch2",isOn: isOn2)
        }
    }
}



回答2:


Here is some alternate approach, which does not require to hardcode interdependently all bindings, but instead use shared storage of bools:

struct DemoExclusiveToggles: View {
    @State var flags = Array(repeating: false, count: 9)
    var body: some View {
        ScrollView {
            ForEach(flags.indices) { i in
                ToggleItem(storage: self.$flags, tag: i, label: "Switch \(i+1)")
                    .padding(.horizontal)
            }
        }
    }
}

struct ToggleItem: View {
    @Binding var storage: [Bool]
    var tag: Int
    var label: String = ""

    var body: some View {
        let isOn = Binding (get: { self.storage[self.tag] },
            set: { value in
                withAnimation {
                    self.storage = self.storage.enumerated().map { $0.0 == self.tag }
                }
            })
        return Toggle(label, isOn: isOn)
    }
}


来源:https://stackoverflow.com/questions/61825396/how-do-i-set-a-group-of-toggles-to-be-mutually-exclusive-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!