moonvader
moonvader

Reputation: 21111

SwiftUI Sheet, Button and ForEach unexpected results

I don't understand behaviour that I see in my SwiftUI app. I have a FormView that is presented inside sheet and used to create or edit entities. I have list of buttons built with foreach that iterates over array of structs. Each button has an action to set entity to be edited

@State var itemToEdit: ItemModel? = nil

.....

List {
 ForEach(items, , id: \.self) { item in 
   Button(action: { 
     itemToEdit = item 
     sheetIsPresented = true
   }, label: { Text(item.name) })
 }
}
.....
.sheet(isPresented: $sheetIsPresented, content: {
   FormView(item: itemToEdit)
})

It works but not all the times, sometimes the form is empty. But if I add .onChange to listen for itemToEdit changes, form is always presented with the expected item.

Upvotes: 0

Views: 51

Answers (1)

malhal
malhal

Reputation: 30746

\.self isn't a valid keypath to an identifier property.

To show an item it is sheet(item: $itemToEdit).

Upvotes: 0

Related Questions