Search code examples
swiftui-foreach

SwiftUI - Popover in ForEach Loop


hopefully anyone can help me with my problem in SwiftUI. I am displaying 30 Buttons in a ForEach loop and any of these Buttons should have their own popover.

My code is currently looking like this:

ForEach(0..<30, id: \.self) { index in
                    
                    Button {
                        
                        presentPopover = true
                        
                    } label: {
                        
                        ZStack {
                            
                            Rectangle()
                                .fill(.white)
                                .frame(width: 180, height: 55)
                                .cornerRadius(5)
                            
                            Text("Runde \(index + 1)")
                                .bold()
                                .font(.system(size: 24))
                                .foregroundColor(.black)
                        }
                        
                    }
                    .popover(isPresented: $presentPopover) {
                        GameSheetPopOverView(points: $points)
                    }
                    
                    
                }

How can i realize this with the $isPresented variable? Currently nothing happens when I tap on one of these Buttons. This only works if I have single elements without a ForEach Loop and a $isPresented variable for each of these elements.

I hope you can help.

Thanks in advance.


Solution

  • Put the stuff in the ForEach in its own View. The index and points should be parameters –