0

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")
        ])
    }
}

1 Answer 1

1

Removing @State of isSelected variable in TagView resolved the issue

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.