如何以编程方式从SwiftUI导航堆栈弹出UIViewControllerRepresentable

时间:2020-05-31 00:15:16

标签: swift swiftui navigationview navigationlink uiviewcontrollerrepresentable

这是我的SwiftUI设置:

我有一个SwiftUI视图(称为MapSearchView),该视图具有包含NavigationLink的NavigationView。

    var body: some View {
    VStack {
        NavigationView {
            Form {
                Section (header: Text("Location")){
                    NavigationLink (locationString, destination: GooglePlacesViewController(mapTools: $mapTools))
                }...

NavigationLink的目标是包装了GooglePlacesViewController的UIViewControllerRepresentable。当我完成GooglePlaces搜索后(无论是因为我做了选择还是取消了搜索),我都希望以编程方式弹出回到MapSearchView。

我尝试在UIViewControllerRepresentable(GooglePlacesViewController)中添加以下内容:

    @Environment(\.presentationMode) var presentationMode

var popToPrevious : Bool = false {
    didSet {
        if popToPrevious == true {
            self.presentationMode.wrappedValue.dismiss()
        }
    }
}

,然后在我的协调器中使用以下方式将popToPrevious设置为true

parent.popToPrevious = true

它确实被调用了,但是什么也没做。

我也曾尝试在协调器中致电

view.viewController().navigationController.popViewController(animated: true)

(viewController()是获取任何视图的viewController的扩展)

这也不起作用。

想法?

1 个答案:

答案 0 :(得分:1)

如果您创建具有所有者视图(例如,可代表)的协调器,则尝试在需要时直接致电

ownerView.presentationMode.wrappedValue.dismiss()