SwuiftUI check mark single row

Viewed 3036

on my project in SwiftUi I'm listing some data in a form, I want to give the user the ability to select a single item in the list with the tap action( can not select more than one in the list)

on the code below I have create a list:

List {
 ForEach(listOfCycle, id: \.self) {db in
      dbList(db: db, ciclo: self.$cycleSelected)
       }
 }

and for each row I have the view dbList

import SwiftUI

struct dbList: View {
    @State var db : Cycle
    @Binding var ciclo : Cycle?
    @State var cicloSelected : Bool = false
    
    var body: some View {
        HStack{
            Text("Database:")
            Spacer()
            Text(db.idDatabaseAirports ?? "").foregroundColor(self.cicloSelected ? .green: .black).font(self.cicloSelected ? .title : .body)
            if self.cicloSelected {
                Image(systemName: "checkmark.circle")
            }
        }.onTapGesture {
            self.cicloSelected.toggle()
            self.ciclo = self.db
            
        }
    }
}

the logic work but the user can tap on multiple row and select more than one, on my project I have to put the checkmark only on one row at the time can't be more than one.

is there any way I can put to avoid multiple selection.

Thanks a lot

1 Answers

The provided code is not testable, so only idea (scratchy, but should be clear).

Note: make sure that Cycle is Equatable

struct dbList: View {
    @State var db : Cycle
    @Binding var ciclo : Cycle?
    
    var body: some View {
        HStack{
            Text("Database:")
            Spacer()
            Text(db.idDatabaseAirports ?? "").foregroundColor(self.db == self.cyclo ? .green: .black).font(self.cicloSelected ? .title : .body)
            if self.db == self.cyclo {
                Image(systemName: "checkmark.circle")
            }
        }.onTapGesture {
            self.ciclo = self.db
            
        }
    }
}
Related