带有ForEach项行的VStack,但只选择了一个Toggle按钮



我在SwiftUI中有一个带有VStack、ForEach和@State Bool的视图。

struct mainView {
@State var selected: Bool

public var body: some View {

VStack(spacing: 0) {

ForEach(viewModel.countryCodeResults, id:.self) { 
countryCodeResult in
ResultRow(result: countryCodeResult, selected: $selected)  
}
}
}
}

我将选定的bool作为绑定传递给ResultRow((视图。

ResultRow((内部的每一行都由一个Text((和toggle组成。

我需要让用户只选择一个切换,而不是多个切换。

因此,每次用户点击切换时,都应该只启用该特定行中的切换,而禁用其他行中的所有切换。使用@State或@Binding 这怎么可能

public struct ResultRow {
@Binding var selected: Bool
public var body: some View {

HStack (spacing:10) {

Text("Toggle text")

Spacer()

Toggle("", isOn: $selected)
.toggleStyle(.radioButton)
.frame(maxWidth: 30)

}

}
.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
.onTapGesture {
selected.toggle()
}

感谢您的帮助。

这里有一种方法。让selected跟踪所选的国家。""表示未选择任何国家。每个结果行都有一个国家/地区名称和selected绑定,并且在选中时将其country分配给selected。每一行将根据selected:的当前设置自行设置样式

struct ContentView: View {

let countries = ["Australia", "Brazil", "Canada", "China", "France", "Egypt", "India"]
@State private var selected = ""

public var body: some View {

VStack(spacing: 0) {

ForEach(countries, id:.self) { country in
ResultRow(country: country, selected: $selected)
}
}
}

}
public struct ResultRow: View {

let country: String
@Binding var selected: String
@State private var isOn = false

public var body: some View {

HStack (spacing:10) {
Text(country)
Spacer()
Toggle("", isOn: $isOn)
.toggleStyle(.button)
.frame(maxWidth: 30)
}

.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
.onChange(of: selected) { _ in
isOn = (country == selected)
}
.onTapGesture {
isOn.toggle()
selected = isOn ? country : ""
}
.onAppear {
isOn = (country == selected)
}

}
}

注意:如果必须始终选择一个项目,则将.onTapGesture { }更改为:

.onTapGesture {
isOn = true
selected = country
}

并将CCD_ 8的初始值设置为其中一个选项。