I wanted to show a list of tags that can be selectable and want to make sure only one tag is selected in the list.
I tried to use @State, @ObservedObject, and @Published, but no luck. What is the best solution here?
import SwiftUI
struct Tag: Identifiable {
let id: Int
let name: String
var selected: Bool = false
}
struct ContentView: View {
@State var tags: [Tag]
var body: some View {
VStack {
ForEach(tags) { tag in
TagView(name: tag.name, isSelected: tag.selected) {
for (index, _) in tags.enumerated() {
// select only one tag
tags[index].selected = tags[index].id == tag.id
}
}
}
}
}
}
struct TagView: View {
let name: String
@State var isSelected: Bool
var onAction: (() -> Void) = { }
var body: some View {
Button(action: onAction) {
Text(name)
.foregroundColor(.white)
.padding()
.background(
isSelected ? Color.red : Color.blue
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(tags: [
Tag(id: 1, name: "Swift"),
Tag(id: 2, name: "Xcode"),
Tag(id: 3, name: "Apple")
])
}
}