我想拥有三个SwiftUI Toggles并具有它们,以便在其中一个处于打开状态时,另外两个处于关闭状态。
使用UIKit做类似事情的老方法是didSet {},这不是SwiftUI的正确方法。我不知道是否有必要深入研究Combine来解决这个表面上看起来应该很简单的问题。
import SwiftUI
// Mutually exclusive toggle switches: when one toggle is on, the other two should be off. This is a start, where to go from here?
struct Junk: View {
@State private var isOn1:Bool = true
@State private var isOn2:Bool = false
@State private var isOn3:Bool = false
var body: some View
{
VStack
{
Toggle("T1", isOn: $isOn1)
Toggle("T2", isOn: $isOn2)
Toggle("T3", isOn: $isOn3)
}
}
}
struct Junk_Previews: PreviewProvider
{
static var previews: some View
{
Junk()
}
}
答案 0 :(得分:9)
由于我不知道您的设计面临什么挑战,因此我将不讨论是否是正确的方法(除非这是您的问题)。但是,要实现您的要求,可以使用中介绑定:
struct Junk: View {
@State private var isOn1:Bool = true
@State private var isOn2:Bool = false
@State private var isOn3:Bool = false
var body: some View
{
let on1 = Binding<Bool>(get: { self.isOn1 }, set: { self.isOn1 = $0; self.isOn2 = false; self.isOn3 = false })
let on2 = Binding<Bool>(get: { self.isOn2 }, set: { self.isOn1 = false; self.isOn2 = $0; self.isOn3 = false })
let on3 = Binding<Bool>(get: { self.isOn3 }, set: { self.isOn1 = false; self.isOn2 = false; self.isOn3 = $0 })
return VStack
{
Toggle("T1", isOn: on1)
Toggle("T2", isOn: on2)
Toggle("T3", isOn: on3)
}
}
}