Swiftui 我能';t使用按钮关闭模态,然后从导航栏再次打开它

Swiftui 我能';t使用按钮关闭模态,然后从导航栏再次打开它,swiftui,presentmodalviewcontroller,Swiftui,Presentmodalviewcontroller,我试图从模态内部关闭模态。问题是,我想从NavigationBarItem打开模式。我提供了一些演示代码和案例,在哪些情况下有效,哪些情况下无效: 案例01 1. Openning from NavigationBarItem 2. Closing by pressing Button in Modal 3. Openning again from Button -> WORKS 案例02 1. Openning from NavigationBarItem 2. Closing by

我试图从模态内部关闭模态。问题是,我想从
NavigationBarItem
打开模式。我提供了一些演示代码和案例,在哪些情况下有效,哪些情况下无效:

案例01

1. Openning from NavigationBarItem
2. Closing by pressing Button in Modal
3. Openning again from Button -> WORKS
案例02

1. Openning from NavigationBarItem
2. Closing by swiping down
3. Openning again from NavigationBarItem -> WORKS
案例03

1. Openning from Button
2. Closing from Button
3. Openning again from NavigationBarItem -> DOESNT WORK
->问题似乎是,当我按下按钮关闭时,模式关闭,但在后台仍标记为活动。之后按NavigationBarButton时,控制台中出现以下错误:

Warning: Attempt to present <_TtGC7SwiftUIP13$7fff2c684d1c22SheetHostingControllerVS_7AnyView_: 0x7f9a6c52b3c0>  on <UINavigationController: 0x7f9a6d85c200> which is already presenting (null)

有了这个问题,我做了以下工作:


struct TestView: View {

    @State var showModal: Bool = false

    var body: some View {
        NavigationView {
            Button(action: {
                self.showModal.toggle()
            }) {
                Text("Show Modal")
            }
            .navigationBarItems(trailing:
                Button(action: {
                    self.showModal.toggle()
                }) {
                    Text("Show Modal")
                }
            )
        }.sheet(isPresented: $showModal) {
            ModalView()
        }
    }
}

struct ModalView: View {
    @Environment(\.presentationMode) var presentationMode

    func dismiss() {
        self.presentationMode.wrappedValue.dismiss()
    }

    var body: some View {
        Button(action: {
            self.dismiss()
        }) {
            Text("Save").bold()
        }
    }
}



我希望这有帮助

你真的改变了什么吗?我似乎找不到区别:DOh nvm我找到了更改,但这似乎没有为我解决问题:/听到这个消息我很抱歉。我会检查我是否可以复制@nOk我将
工作表
移到了外部,因为根据我的理解,模态需要位于UI元素的外部级别。对我来说,这个解决方案有效。。。您是否已将TestView包装在其他内容中?

struct TestView: View {

    @State var showModal: Bool = false

    var body: some View {
        NavigationView {
            Button(action: {
                self.showModal.toggle()
            }) {
                Text("Show Modal")
            }
            .navigationBarItems(trailing:
                Button(action: {
                    self.showModal.toggle()
                }) {
                    Text("Show Modal")
                }
            )
        }.sheet(isPresented: $showModal) {
            ModalView()
        }
    }
}

struct ModalView: View {
    @Environment(\.presentationMode) var presentationMode

    func dismiss() {
        self.presentationMode.wrappedValue.dismiss()
    }

    var body: some View {
        Button(action: {
            self.dismiss()
        }) {
            Text("Save").bold()
        }
    }
}