Search code examples
ioslifecycleswiftuiios-navigationview

Lifecycling in SwifUI: Running code when leaving a child view of a NavigationView hierarchy


With SwiftUI's NavigationView we benefit from simplicity with code construction. However, not exposed, at least in these early stages are the overrides. Further, the reduced focus on managing the LifeCycle of views makes it difficult to find out what and when to call something based on the state of the view.

I would like to run some code when a user chooses to go back up a NavigationView hierarchy (i.e. click the back button supplied by NavigationView).

I've tried onDisappear() {} and it's other variants and I cannot get it to work. It seems like it is not called. The onAppear() {} does work so I'm stumped.

Any help would be SUPER APPRECIATED!


Solution

  • I'm quite certain that at this stage, there is no method that can be override to catch the 'back' action of the navigation view.

    However, I did figure out that I can hide the NavigationView's back button and add a custom one myself where I can call the code before dismissing the child.

    import SwiftUI
    
    struct SecondView: View {
        var body: some View {
    
    
            Text("Second View")
                .navigationBarBackButtonHidden(true)
                .navigationBarItems(leading: NavigationViewCustomBack())
        }
    
    
    }
    
    
    ==========================
    
    import SwiftUI
    
    struct NavigationViewCustomBack: View {
        var body: some View {
            HStack{
                    Image(systemName: "chevron.left").foregroundColor(.blue).font(Font.title.weight(.medium))
                    Text("Home").padding(.leading, -5)
                }
        }
    }
    
    struct NavigationViewCustomBack_Previews: PreviewProvider {
        static var previews: some View {
            NavigationViewCustomBack()
        }
    }