微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI 模式关闭

如何解决SwiftUI 模式关闭

我想通过点击我调用它的同一个按钮或点击屏幕上的任意位置来关闭模式。

但是当弹出窗口弹出时,它不允许我与它们任何一个交互。能否请您给我一个解决方案?

ZStack{
                Color.black.opacity(0.4)
                    .edgesIgnoringSafeArea(.all)
                    .animation(.none)
                vstack{
                    Circle().fill(Color.orange)
                        .frame(width: 70,height: 70)
                        .overlay(Image(systemName: "questionmark.circle").font(.system(size: 50)).foregroundColor(.white
                        ))
                        .offset(y: 40)
                        .zIndex(1)
                    vstack{
                        Color.orange.frame(height: 40)
                        Spacer()
                        Text("Let the popup open")
                        Spacer()
                        Button("Present!") {
                            isPresented.toggle()
                        }
                        .fullScreenCover(isPresented: $isPresented){
                            FullScreenModalView(showPopUP: $showPopUp)
                        }.padding(.vertical,12)
                        .frame(maxWidth: .infinity)
                        .background(Color.orange)
                    }.background(Color.white)
                    .cornerRadius(12)
                }.frame(height: 250)
                .background(Color.clear)
                .padding(.horizontal,35)
                .offset(y: 150)
                .scaleEffect(x: showPopUp ? 1 : 0.8,y: showPopUp ? 1 : 1.3)
                .animation(.interactiveSpring(response: 0.3,dampingFraction: 0.3),value: animate)
            }.opacity(showPopUp ? 1 : 0)

解决方法

你的例子没有包含足够的代码来编译,所以我做了一个更小的、最小的例子来展示这个想法:

struct ContentView: View {
    @State var modalPresented = false
    
    var body: some View {
        Button(action: {
            modalPresented.toggle()
        }) {
            Text("Present")
        }.fullScreenCover(isPresented: $modalPresented) {
            ModalContent(presented: $modalPresented)
        }
    }
}

struct ModalContent : View {
    @Binding var presented : Bool
    
    var body: some View {
        VStack {
            Text("Modal content")
        }
        .frame(maxWidth: .infinity,maxHeight: .infinity)
        .background(
            Color.green.edgesIgnoringSafeArea(.all)
                .onTapGesture {
                    presented = false
                }
        )
        //.contentShape(Rectangle())
        //.onTapGesture { presented = false }
    }
}

根据定义,由于您使用的是全屏覆盖,您将无法与原始按钮进行交互 - 它会被覆盖。

在我的示例中,我使用模态的背景来响应点击手势来关闭模态,但我还注释掉了几行,您可以在其中使用 contentShape主堆栈并在那里捕获点击手势。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。