Home > other >  @State variable in onTapGesture not getting updated
@State variable in onTapGesture not getting updated

Time:02-02

with the code below I was expecting when the image in VStack was tapped, it shows another image in the full screen cover but the imageName variable does not seem to get set to jugg as in the new full screen it has only a gray background

struct TestView: View {
    @State var imageName = ""
    @State var showFullscreen = false

    var body: some View {
        VStack {
            Image("drow")
                .resizable()
                .scaledToFit()
                .frame(width: 100)
                .onTapGesture {
                    self.imageName = "jugg"
                    self.showFullscreen = true
            }
        }
        .fullScreenCover(isPresented: $showFullscreen) {
            ZStack {
                Color.gray.ignoresSafeArea()
                Image(imageName)
                    .resizable()
                    .scaledToFit()
                    .frame(width: 380)
            }
        }
    }
}

CodePudding user response:

as mentioned in the comments, use the .fullScreenCover(item: ..) version of the fullScreenCover, such as:

struct ImageName: Identifiable {
    let id = UUID()
    var name = ""
}

struct TestView: View {
    @State var imageName: ImageName?
    
    var body: some View {
        VStack {
            Image("drow").resizable().scaledToFit().frame(width: 100)
                .onTapGesture {
                    imageName = ImageName(name: "drow")
                }
        }
        .fullScreenCover(item: $imageName) { img in
            ZStack {
                Color.gray.ignoresSafeArea()
                Image(img.name).resizable().scaledToFit().frame(width: 380)
            }
        }
    }
}

CodePudding user response:

Seems to only work if you create a separate SwiftUI view and pass in the imageName as a @Binding variable

struct TestView: View {
    @State var imageName = ""
    @State var showFullscreen = false
    
    var body: some View {
        VStack {
            Image("drow")
                .resizable()
                .scaledToFit()
                .frame(width: 100)
                .onTapGesture {
                    
                    imageName = "jugg"
                    
                    showFullscreen = true
                }
        }
        .fullScreenCover(isPresented: $showFullscreen) {
            CoverView(imageName: $imageName)
        }
    }
}
struct CoverView: View {
    
    @Binding var imageName: String
    
    var body: some View {
        ZStack {
            Color.gray.ignoresSafeArea()
            Image(imageName)
                .resizable()
                .scaledToFit()
                .frame(width: 380)
        }
    }
}
  •  Tags:  
  • Related