swiftuiswiftui-navigationview

how do i render a custom back button when using .fullscreencover to present a full screen modal view


i am learning about swiftUI navigation stack, i am trying to implement a custom back button when presenting a view using .fullscreencover, but i am stuck trying to render the back button.


import SwiftUI

struct navigation1: View {
    @Binding var isPresented: Bool
    
    var backButtonPlacement: ToolbarItemPlacement {
            #if os(iOS)
            ToolbarItemPlacement.navigationBarLeading
            #else
            ToolbarItemPlacement.navigation
            #endif
        }
    var body: some View {
        ZStack {
            Color(.yellow)
            
            VStack{
                Text("First Page")
                    .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
            }
            
        }
        .navigationTitle("page 1")
        .navigationBarBackButtonHidden(true)
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button {
                    isPresented = false
                } label: {
                    Image(systemName: "arrow.backward.circle.fill")
                        .symbolVariant(.circle.fill)
                        .font(.title)
                        .foregroundStyle(.black)
                }
            }
        }
        .ignoresSafeArea(.all)
        .frame(width: .infinity)
    }
}

#Preview {
    navigation1(isPresented: .constant(true))
}

this is the preview

Please can someone explain what to do so that I can learn and take note of it for future references. Thanks in advance

i tried to comment out .navigationBarBackButtonHidden(true) to see if the default toolbar would render, but it didnt work either


Solution

  • You're missing Navigation outside the View. Basically you must have a NavigationBar before you can decorate it. Add the below code:

    var body: some View {
        NavigationStack { //<- here
            ZStack { ... }
        }
    }