25

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.

enter image description here

What am I doing wrong, how do you put a navigation bar on a modal sheet?

iSpain17
  • 2,502
  • 3
  • 17
  • 26

2 Answers2

44

You have to wrap your modal view in a NavigationView like this

@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: {}))
        }
    }
}
Kamchatka
  • 3,597
  • 4
  • 38
  • 69
LuLuGaGa
  • 13,089
  • 6
  • 49
  • 57
3

Modal view must be wrapped in NavigationView but the above solution using .navigationBarItems(trailing: Button("Done", action: {})) is not working for me. 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). So this is part of my ModalView code:

  var body: some View {
        VStack (alignment: .leading, spacing: 10) {
            header
            infoBody
            Spacer()
        }
        .padding()
        .navigationBarItems(leading: btnBack)
        .navigationBarTitle("", displayMode: .inline)
    }
Mahmud Ahsan
  • 1,755
  • 19
  • 18