Search code examples
iosswiftswiftuiios14

@State var not updated as expected in LazyVGrid


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)
    
    }
}

}


Solution

  • Sheet is picky about when it loads its content with isPresented.

    A more reliable solution is to use sheet(item: ), which will work with your situation with just a small modification to selectedItem -- it'll have to conform to Identifiable. So, you can wrap it like this:

    struct ImageSelection : Identifiable {
            var name : String
            var id: String {
                return name
            }
        }
    

    Then, selectedItem will become an optional, because it will determine whether the sheet is open. Here's a minimal example showing the optional and how you use it with sheet(item:):

    struct ContentView : View {
        @State var selectedItem : ImageSelection?
        
        var body: some View {
            Text("Test")
                .sheet(item: $selectedItem) { item in
                    Text(item.name)
                }
        }
    }
    

    (Note that item is passed into the sheet's closure -- that's how you make sure that the correct data is used)

    Update Based on your comments:

    selectedItem = ImageSelection(name: imageSet[index].name)
    print(selectedItem?.name)