ios 如何在Swift中将一组切换设置为互斥

exdqitrt  于 2023-05-08  发布在  iOS
关注(0)|答案(3)|浏览(166)
@State private var isOn1 = false
@State private var isOn2 = false

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

这是我目前所知道的。有没有一种方法可以让我在激活一个切换时添加一个if语句,使所有其他切换都关闭。或者是有无论如何改变状态的切换时,激活一个。任何答案都很感激,谢谢!

vfh0ocws

vfh0ocws1#

这里有一些替代方法,它不需要相互依赖地硬编码所有绑定,而是使用布尔值的共享存储:

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)
    }
}
wfypjpf4

wfypjpf42#

您可以将isOn2定义为Binding。您可以通过传入getter的闭包和setter的闭包来创建Binding。对于isOn2Binding,您只需返回isOn1的求反值,并在其setter中将isOn1设置为传入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)
        }
    }
}
vcirk6k6

vcirk6k63#

这里有一个更简单的解决方案和更实用的示例。跟踪活动选择,并创建一个绑定来检查和设置活动选择

struct Item: Identifiable, Hashable {
  var name: String
  let id: UUID = .init()
}

struct ContentView: View {
  @State var items: [Item] = [Item(name: "Item 1"),
                              Item(name: "Item 2"),
                              Item(name: "Item 3")]

  @State var activeItem: Item!

  init() {
    _activeItem = State(initialValue: items[0])
  }

  var body: some View {
    List(items) { item in
      HStack {
        Text(item.name)
        let isOn = Binding<Bool>(get: { activeItem == item },
                                 set: { _ in activeItem = item })
        Toggle("", isOn: isOn)
      }
    }
  }
}

相关问题