Home > Enterprise >  SwiftUI onDisappear not being called
SwiftUI onDisappear not being called

Time:03-31

I am using a ScrollView and VStack to present bunch of views in a list. But for some reason the onDisappear is not being called, the onAppear was though.

Does onDisappear only call when that view has disappeared off the screen? Or when it's deinitialized

struct AView: View {
        
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack {
                ForEach(0...99, id: \.self) { _ in
                    SomeView()
                        .onDisappear {
                            print("Disappeared")
                        }
                }
            }
        }
    }
}

CodePudding user response:

When you're using VStack, it's gonna draw all the views inside - all of them are added to the view tree, it doesn't matter wether it's visible on the screen.

If you replace it with LazyVStack it'll make content lazy - only visible views will be added to the view tree and onDisappear will be called as you expect it.

  • Related