简体   繁体   English

SwiftUI 从模态视图使用 NavigationLink 推送视图

[英]SwiftUI Push View with NavigationLink from modal view

I present a modal view with fullScreenCover by pressing "present my modal" button:我通过按下“呈现我的模态”按钮来呈现带有fullScreenCover的模态视图:

struct ContentView: View {

    @State var presentMyModal = false

    var body: some View {
        Text("Hello, world!")
            .fullScreenCover(isPresented: $presentMyModal) {
                    MyModalView()
            }
        Button(action: { presentMyModal = true },
               label: { Text("present my modal")})
    }
}

Then I want to push a new view with NavigationLink from this modal:然后我想从这个模式中使用NavigationLink推送一个新视图:

struct MyAlertView: View {

    @State var pushNavigationLinkedView = false

    var body: some View {
        Text("MyAlertView")
            .padding()
        Button(action: { pushNavigationLinkedView = true },
               label: { Text("push navigation linked view")})

        NavigationLink(destination: NavigationLinkedView(),
                       isActive: $pushNavigationLinkedView) {
            EmptyView()
        }
    }
}

And here is my NavigationLinkedView :这是我的NavigationLinkedView

struct NavigationLinkedView: View {
    var body: some View {
        Text("NavigationLinkedView")
            .padding()
    }
}

But nothing happens when I press "push navigation linked view" button.但是当我按下“推送导航链接视图”按钮时没有任何反应。

So is it allowed by apple guideline to push a view with NavigationLink from a modal view?那么苹果指南是否允许从模态视图推送带有NavigationLink的视图? If yes, what is the best way to do it?如果是,最好的方法是什么?

Tested on iOS15 and XCode 13在 iOS15 和 XCode 13 上测试

So is it allowed by Apple guideline to push a view with NavigationLink from a modal view?那么 Apple 指南是否允许从模态视图推送带有NavigationLink的视图?

Yes.是的。 Just make sure you have a NavigationView at the base of MyAlertView .只需确保在MyAlertView的底部有一个NavigationView The modal sheet creates a new view hierarchy, and NavigationLink only works when there's a NavigationView somewhere in the hierarchy above.模态表创建一个新的视图层次结构,而NavigationLink仅在上面的层次结构中某处存在NavigationView时才起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM