Row selection formatting

Hello everyone!

I am trying to build an app that has a quizzer. Users need to select an answer they think is correct. I want the selected answer to be highlighted, but users should be able to change their answer. I currently have it working that the answer is highlighted, but when i choose another answer, multiple options are highlighted. How can i change it, so that when i choose a different answer, the other one is no longer highlighted?

Here is my AnswerRow component used to display the answers:

import SwiftUI

struct AnswerRow: View {
    
    var answer: Answer
    
    @State private var isSelected = false
    
    var selectedColor = Color(.black)
    
    var body: some View {
        HStack(spacing: 20) {
            Image(systemName: "circle.fill")
                .font(.caption)
            
            Text(answer.answerText)
                .bold()
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(.white)
        .cornerRadius(10)
        .overlay (
        RoundedRectangle(cornerRadius: 20)
            .stroke(isSelected ? selectedColor : .gray, lineWidth: 2)
        )
        .onTapGesture {
            isSelected = true
        }
    }
}

Here is the way i am implementing it in a view:

(...)
                AnswerRow(answer: Answer(id: 0, answerText: "Answer 1"))
                AnswerRow(answer: Answer(id: 01, answerText: "Answer 2"))
                AnswerRow(answer: Answer(id: 02, answerText: "Answer 3"))

(...)

If you have any other tips / suggestions for my code, feel free! Thanks in advance for the help!

You could:

  • create a State var in the view that contains the Rows
@State var selectedRows = [Bool]()
  • initialise all to false; you can do it in .onAppear

  • add an index var in AnswerRow to know to which item of selectedRows

var rowIndex : Int  // to be initialised with row index; you could declare @State and initialise in .onAppear of the Row
  • change onTapGesture to update selectedRows: first turn all to false then turn the selected row to true
            .stroke(selectedRows[rowIndex] ? selectedColor : .gray, lineWidth: 2)
Row selection formatting
 
 
Q