0

I have a view that displays multiple images fetched from Firebase in a VStack. Each image is a button, the button opens a sheet and it displays the image and text that goes with it. When I dismiss the sheet and press on a different image the same data comes up. How do I refresh these paramaters

VStack View with images as buttons:

@State var dic = OrderedDictionary<String, UIImage>() VStack (alignment: .center) { ForEach(dic.keys, id: \.self) { dicObject in Button { showingSheet.toggle() } label: { Image(uiImage: dic[dicObject]!) .resizable() .frame(width: 300, height: 400) .cornerRadius(20) } .sheet(isPresented: $showingSheet) { GalleryViewSpecific(image: dic[dicObject]!, url: dicObject) } } } 

View specific image view used by .sheet

//@State var image: UIImage @State var image: UIImage @State var url: String @Environment(\.dismiss) var dismiss var body: some View { ScrollView { VStack(alignment: .leading) { Button("Press to dismiss") { dismiss() } .font(.title) .padding() .background(.black) Image(uiImage: image) .resizable() .frame(width: 300, height: 400) .cornerRadius(20) Text(url) .foregroundColor(.white) } } .background(Color.black) } 
5
  • Move your sheet outside the ForEach and use sheet(item:) instead of sheet(isPresented:) Commented Jan 11, 2023 at 15:14
  • If I move sheet outside of the ForEach 'dicObject' is not in the scope Commented Jan 11, 2023 at 15:39
  • Please update your code to show a minimal example that reproduces the issue; ideally a struct ContentView that someone can paste into Xcode and run. Please take a look at minimal reproducible example Commented Jan 11, 2023 at 15:44
  • @Bart that is why you use the sheet(item:) form I suggested. You'll set the item to your object inside the Button action Commented Jan 11, 2023 at 16:51
  • ForEach is not a for loop Commented Jan 16, 2023 at 16:24

1 Answer 1

1

Store the displayed item when you tap the button inside the ForEach:

import SwiftUI struct ContentView: View { struct Item: Identifiable { let id = UUID() let text: String } let items = [Item(text: "1"), Item(text: "2")] @State var selectedItem: Item? var body: some View { VStack { ForEach(items, id: \.id) { item in Button(action: { selectedItem = item }) { Text(item.text) } } .sheet(item: $selectedItem) { selectedItem in Text(selectedItem.text) } } .padding() } } 

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need the onDismiss -- this will happen automatically
@jnpdx even nicer; edited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.