I'm having trouble understanding why my variable "selectedItem" is being updated in one part of this code, and not the other. My goal is to make it so when you tap on the image in the grid, it passes the selected image name to an ImageDetailView (ideally I'd like it to be a Navigationlink, but a sheet is easier for me to test.. one step at a time).
Where I have print(selectedItem)
it prints the name of the LazyVGrid's tapped Image in the console as expected. Awesome.
But then the sheet that opens is blank because it's looking for "test" still... the console shows a message saying "No image named 'test' found in asset catalog..."
Why is the sheet still using the initialized value of "test?" and not the updated value?
struct ImagesView: View {
@State var gridLayout: [GridItem] = [ GridItem() ]
var title: String
var imageSet = [Photo]()
@State private var selectedItem = "test"
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
GeometryReader { reader in
ScrollView {
LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) {
ForEach(imageSet.indices) { index in
Image(imageSet[index].name)
.resizable()
.onTapGesture {
showImageDetailView = true
selectedItem = imageSet[index].name
print(selectedItem)
}
)}
.padding(.horizontal, 10)
.padding(.bottom, 25)
}
.sheet(isPresented: $showImageDetailView, content: {
ImageDetailView(selectedItem: selectedItem)
})
Here's the ImageDetailView
struct ImageDetailView: View {
@State var selectedItem: String
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
Image(selectedItem)
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(10)
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…