Open Modal

I have a ForEach listing a lot of eventos, having 1 image button for each of them.

When the button is clicked, I will open a modal with the selectedEvento.

The problem is even though I've the line "self.selectedEvento = evento" inside of the button actions, when I click the button for the first time, the selectedEvento is being passed as nil.

However if I click a second button, the process will happen succesfully.

Code:
...
@State var showModal = false
@State var selectedEvento: Evento!
...

ForEach(store.eventos) { evento in
          VStack() {
            Button(action: {
              self.selectedEvento = evento
              self.showModal.toggle()
               
            }) {
            WebImage(url: evento.thumbnail)
            }
          }
          .sheet(isPresented: $showModal) {
            if self.selectedEvento != nil {
              //open detailView
            } else {
              Text("Some Error State goes here")
            }
          }
        }
  • ** Why is this happening ?

Shoudn't the first click also to be passing the selectedEvento ? Why it doesnt happen ?

Thx
Answered by OOPer in 669905022

Shoudn't the first click also to be passing the selectedEvento ? Why it doesnt happen ?

It is a known issue that @State variables do not work when used in the closure of sheet.
A possible workaround is making another View from the content of the sheet:
Code Block
struct MyView: View {
//...
var body: some View {
//...
.sheet(isPresented: $showModal) {
MySheetView(selectedEvento: self.$selectedEvento)
}
//...
}
}
struct MySheetView: View {
@Binding var selectedEvento: Evento?
var body: some View {
if self.selectedEvento != nil {
//open detailView
} else {
Text("Some Error State goes here")
}
}
}


You can find some other threads showing how to workaround the @State and sheet issue,
for example: https://developer.apple.com/forums/thread/677454 .
Accepted Answer

Shoudn't the first click also to be passing the selectedEvento ? Why it doesnt happen ?

It is a known issue that @State variables do not work when used in the closure of sheet.
A possible workaround is making another View from the content of the sheet:
Code Block
struct MyView: View {
//...
var body: some View {
//...
.sheet(isPresented: $showModal) {
MySheetView(selectedEvento: self.$selectedEvento)
}
//...
}
}
struct MySheetView: View {
@Binding var selectedEvento: Evento?
var body: some View {
if self.selectedEvento != nil {
//open detailView
} else {
Text("Some Error State goes here")
}
}
}


You can find some other threads showing how to workaround the @State and sheet issue,
for example: https://developer.apple.com/forums/thread/677454 .
Open Modal
 
 
Q