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

后端 未结 2 545
甜味超标
甜味超标 2020-12-22 07:26
@State private var isOn1 = false
@State private var isOn2 = false

var body: some View {
    ScrollView{
        Toggle(\"switch1\",isOn:$isOn1)
        Toggle(\"swi         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-22 08:04

    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(
                get: { !self.isOn1 },
                set: { self.isOn1 = !$0 }
            )
            return ScrollView{
                Toggle("switch1",isOn: $isOn1)
                Toggle("switch2",isOn: isOn2)
            }
        }
    }
    

提交回复
热议问题