SwiftUI: Dismiss View Within macOS NavigationView

别等时光非礼了梦想. 提交于 2020-02-22 07:41:07

问题


As detailed here (on an iOS topic), the following code can be used to make a SwiftUI View dismiss itself:

@Environment(\.presentationMode) var presentationMode
// ...
presentationMode.wrappedValue.dismiss()

However, this approach doesn't work for a native (not Catalyst) macOS NavigationView setup (such as the below), where the selected view is displayed alongside the List.

Ideally, when any of these sub-views use the above, the list would go back to having nothing selected (like when it first launched); however, the dismiss function appears to do nothing: the view remains exactly the same.

Is this a bug, or expected macOS behaviour?

Is there another approach that can be used instead?

struct HelpView: View {

    var body: some View {

        NavigationView {
            List {
                NavigationLink(destination:
                    AboutAppView()
                ) {
                    Text("About this App")
                }
                NavigationLink(destination:
                    Text("Here’s a User Guide")
                ) {
                    Text("User Guide")
                }
            }
        }
    }
}

struct AboutAppView: View {

    @Environment(\.presentationMode) var presentationMode

    public var body: some View {
        Button(action: {
            self.dismissSelf()
        }) {
            Text("Dismiss Me!")
        }
    }

    private func dismissSelf() {
        presentationMode.wrappedValue.dismiss()
    }
}

FYI: The real intent is for less direct scenarios (such as triggering from an Alert upon completion of a task); the button setup here is just for simplicity.

来源:https://stackoverflow.com/questions/59361491/swiftui-dismiss-view-within-macos-navigationview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!