简体   繁体   English

SwiftUI 中的模态表可以有导航栏吗?

[英]Can a Modal Sheet have a Navigation Bar in SwiftUI?

I am presenting a modal sheet from a navigation bar button in my code:我在我的代码中从导航栏按钮显示一个模式表:

struct MainPage : View {

    @State var isModalSheetShown: Bool = false

    var body: some View {
        VStack {
            [...]
        }
        .navigationBarItems(trailing: HStack {
            Button(action: { self.isModalSheetShown = true }) {
                Text("Add")
            }
        })
        .sheet(isPresented: $isModalSheetShown, content: {
            VStack {
                [...]
            }
            .navigationBarItems(trailing: HStack {
                Button(action: { ... }) {
                    Text("Done")
                })
            })
        })
    }
}

But the Navigation Bar does not appear in the modal sheet as you can see below.但是导航栏没有出现在模态表中,如下所示。

在此处输入图片说明

What am I doing wrong, how do you put a navigation bar on a modal sheet?我做错了什么,你如何在模态表上放置导航栏?

You have to wrap your modal view in a NaviagtionView like this您必须像这样将模态视图包装在NaviagtionView

@State var isModalSheetShown: Bool = false

var body: some View {
    VStack {
        Text("Main")
    }
    .navigationBarItems(trailing: Button("Add",
                                         action: { self.isModalSheetShown = true }))
    .sheet(isPresented: $isModalSheetShown) {
        NavigationView {
            VStack {
                Text("Modal")
            }
            .navigationBarItems(trailing: Button("Done",
                                                 action: {}))
        }
    }
}

Modal view must be wrapped in NavigationView but the above solution using .navigationBarItems(trailing: Button("Done", action: {})) is not working for me.模态视图必须包含在NavigationView但上述使用.navigationBarItems(trailing: Button("Done", action: {}))解决方案对我不起作用。 What worked for me is, in the modal view I have to add a navigationButton and also to show the navigation bar I have to use the .navigationBarTitle("", displayMode: .inline) .对我有用的是,在模态视图中,我必须添加一个 navigationButton 并显示导航栏,我必须使用.navigationBarTitle("", displayMode: .inline) So this is part of my ModalView code:所以这是我的 ModalView 代码的一部分:

  var body: some View {
        VStack (alignment: .leading, spacing: 10) {
            header
            infoBody
            Spacer()
        }
        .padding()
        .navigationBarItems(leading: btnBack)
        .navigationBarTitle("", displayMode: .inline)
    }

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

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