swift onTapGesture中的@State变量未更新

z9smfwbn  于 2023-03-22  发布在  Swift
关注(0)|答案(3)|浏览(197)

使用下面的代码,当点击VStack中的图像时,它会在全屏封面中显示另一个图像,但 imageName 变量似乎没有设置为 jugg,因为在新的全屏中它只有灰色背景

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

t3psigkw1#

如注解中所述,使用fullScreenCover.fullScreenCover(item: ..)版本,例如:

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

8cdiaqws2#

似乎只有在创建一个单独的SwiftUI视图并将imageName作为@Binding变量传入时才有效

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

swvgeqrz3#

我有类似的问题,我传递@Binding变量到ChildView,它总是在第一个TapGesture失败。相反,我在viewModel中创建了Published变量,并在两个视图中使用它。

相关问题