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?
To change a navigation bar color in SwiftUI, you apply toolbarBackground modifier to the content view of NavigationStack . NavigationView is deprecated in iOS 16. toolbarBackground accepts two parameters. ShapeStyle : The style to display as the background of the bar.
Before NavigationStack and NavigationSplitView , SwiftUI introduced the NavigationView and NavigationLink structs. These two pieces work together to allow navigation between views in your application. The NavigationView is used to wrap the content of your views, setting them up for subsequent navigation.
You have to wrap your modal view in a NaviagtionView
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: {}))
}
}
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With