SwiftUI - change Model from nested subviews

539 views Asked by At

I have a LazyVStack presenting Cells. My main View which has the LazyVStack has a viewModel.

@StateObject private var model = ViewModel()

The Stack presents a list of CustomViews.

LazyVStack {
    ForEach(model.items) { item in
       CustomView(item: item)
    }
}

Each custom view consists from two other subviews, CustomView1 and CustomView2. CustomView2 has a button, where onTap I want to flip the cell.

However at that point my Custom views have a new copy of these items (struct). What is the best approach to point back to the model to achieve:

.onTapGesture {
   model.flipItem(item)
}
  • Somehow multiple @Binding variables is an option ?
  • Making the ViewModel shared singleton for easy access ?
  • Better option ?
1

There are 1 answers

7
aheze On

I would add a property inside your Item struct that stores if the card is flipped or not:

struct Item {
    var ifFlipped = false
    ...
}
model.items = [Item(), Item()]

Then loop over model.items.indices, so that you can get the Binding:

LazyVStack {
    ForEach(model.items.indices, id: \.self) { index in
       CustomView(item: $model.items[index]) /// this will be a Binding<Item>
    }
}

And your CustomView/CustomView1 will need to look something like this.

struct CustomView: View {
    @Binding var item: Item
    
    var body: some View {
        CustomView1(item: $item) /// pass Binding down
    }
}

struct CustomView1: View {
    @Binding var item: Item
    
    var body: some View {
        Text("Hi")
            .onTapGesture {
                item.isFlipped.toggle()
            }
    }
}