简体   繁体   English

SwiftUI onDisappear 未被调用

[英]SwiftUI onDisappear not being called

I am using a ScrollView and VStack to present bunch of views in a list.我正在使用ScrollViewVStack在列表中呈现一堆视图。 But for some reason the onDisappear is not being called, the onAppear was though.但由于某种原因,没有调用onDisappear ,但调用了onAppear

Does onDisappear only call when that view has disappeared off the screen? onDisappear是否仅在该视图从屏幕上消失时才调用? 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")
                        }
                }
            }
        }
    }
}

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.当你使用VStack时,它会在里面绘制所有的视图——所有的视图都被添加到视图树中,无论它在屏幕上是否可见都没有关系。

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.如果你用LazyVStack替换它,它会让内容变得懒惰——只有可见的视图会被添加到视图树中,并且onDisappear会按你期望的那样被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM