Hello,
I am displaying a list of paninis which have a custom cell.
What i am trying to achieve:
I am trying to implement a single selection cell in the panini list. When a panini is selected, his checked property must be set totrue
.
The actual behavior, is a multiselection.
How could i achieve a single selection.
The Panini model
struct Panini: ListableResponseProtocol {
let id = UUID()
let name: String
let price: String
let details:String
var checked:Bool
}
The list
struct PaniniList<Model: ListViewModel>: View{
@ObservedObject var paninisVM : Model
@State var checked: Bool?
var body: some View {
List {
Section(header: VStack {
CustomSectionContent(text: "Vos garnitures")
}
){
ForEach(0..<$paninisVM.pananiDataSource.data.count, id: \.self) { index in
CellView(panini: paninisVM.pananiDataSource.data[index], selection: $paninisVM.pananiDataSource.data[index].checked)
}.buttonStyle(.plain)
}
}
}
}
The cell View
struct CellView: View {
@State var panini: Panini
@Binding var selection: Bool
var body: some View {
HStack{
VStack(alignment: .leading) {
Text(panini.name).font(.callout)
Text(panini.details).font(.callout).foregroundColor(.gray)
}
Spacer()
Image(systemName: panini.checked ? "checkmark" : "plus" )
}
.onTapGesture {
selection = panini.checked
if selection != nil {
panini.checked.toggle()
}
}
}
}
After a couple researches, i tried this but no success.
struct CellView: View {
@State var panini: Panini
@Binding var selection: Bool
var body: some View {
HStack{
VStack(alignment: .leading) {
Text(panini.name).font(.callout)
Text(panini.details).font(.callout).foregroundColor(.gray)
}
Spacer()
if panini.checked == selection {
Image(systemName: "plus")
} else {
Image(systemName: "checkmark" )
}
}
.onTapGesture {
self.selection = self.panini.checked
}
}
}