我如何将一组切换按钮快速设置为互斥的 [英] How do I set a group of toggles to be mutually exclusive in swift
问题描述
@State private var isOn1 = false
@State private var isOn2 = false
var body: some View {
ScrollView{
Toggle("switch1",isOn:$isOn1)
Toggle("switch2",isOn:$isOn2)
}
这是我到目前为止所拥有的.有没有一种方法可以在我激活一个切换开关时关闭所有其他切换开关,从而添加if语句.还是在激活一个开关时改变开关的状态.感谢您提供任何答案!
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!
推荐答案
您可以将 isOn2
定义为 Binding
.您可以通过传入其getter的闭包和其setter的另一个闭包来创建 Binding
.对于您的 isOn2
Binding
,您只需要返回取反的 isOn1
值,然后在其设置器中设置 isOn1
传递给setter的取反值.
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)
}
}
}
这篇关于我如何将一组切换按钮快速设置为互斥的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!