ios – SwiftUI: ViewModifier callback when view is completely removed, like onDisappear but called only once


the onAppear onDisappear modifiers can be called multiple times while the view is part of the hierarchy.

I know that there is a trick to make an onLoad ViewModifier like so

extension View {
    func onLoad(perform action: (() -> Void)? = nil) -> some View {
        self.modifier(ViewDidLoadModifier(action: action))
    }
}

struct ViewDidLoadModifier: ViewModifier {
    @State private var viewDidLoad = false
    let action: (() -> Void)?

    func body(content: Content) -> some View {
        content
            .onAppear {
                if viewDidLoad == false {
                    viewDidLoad = true
                    action?()
                }
            }
    }
}

From the above code, onLoad will only be called once

struct MyView: View {
    var body: some View {
        Text("Hello View")
            .onAppear {
                // may print multiple times
                print("onAppear")
            }
            .onLoad {
               // only prints once
               // when the view first appears in the hierarchy
               print("onLoad")
            }
    }
}

Is there a way to have an onUnLoad ViewModifier?

struct MyView: View {
    var body: some View {
        Text("Hello View")
            .onDisappear {
                // may print multiple times
                print("onDisappear")
            }
            .onUnLoad {
               // only prints once,
               // when the view is completely removed
               print("onUnLoad")
            }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img