SwiftUI PageTabView in iOS14.2 will Recall ChildView onAppear method Many times

前端 未结 3 1572
轮回少年
轮回少年 2021-01-23 23:41

I use TabView PageTabViewStyle with SwiftUI to display a pageview, when I swipe this TabView I find child view will Recall onAppear method Many times, Can someone tell me why?

3条回答
  •  情歌与酒
    2021-01-24 00:08

    Views are preloaded at the discretion of SwiftUI. Sometimes more than others depending on the device's available resources. onAppear is called even if it has appeared out of view (pre-loaded)

    import SwiftUI
    
    struct PageView: View {
        
        @StateObject var vm = PageViewModel()
        
        var body: some View {
            VStack {
                
                DragViewBar().padding(.top, 14)
                
                TabView(selection: $vm.selectTabIndex) {
                    
                    TextView(index: "0").tag(0)
                    TextView(index: "1").tag(1)
                    TextView(index: "2").tag(2)
                    TextView(index: "3").tag(3)
                    TextView(index: "4").tag(4)
                    TextView(index: "5").tag(5)
                    
                }
                //This lets you perform an operation when the value has changed
                .onReceive(vm.$selectTabIndex, perform: { idx in
                    print("PageView :: body :: onReceive" + idx.description)
                })
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                
            }
    
        }
    }
    
    struct TextView: View {
        
        let index: String
        
        var body: some View {
            VStack {
                Text(index)
            }
            //Views are pre-loaded at the discretion of SwiftUI
            .onAppear { print(index) }
            
            .onReceive(index.publisher, perform: { idx in
                print("TextView :: body :: onReceive" + idx.description)
            })
            
        }
    }
    
    struct DragViewBar: View {
        var body: some View {
            Rectangle()
                .frame(width:36.0,height:5.0).foregroundColor(Color.blue)
                .cornerRadius(100)
        }
    }
    
    class PageViewModel: ObservableObject {
        @Published var selectTabIndex = 0
    }
    
    
    struct PageView_Previews: PreviewProvider {
        static var previews: some View {
            PageView()
        }
    } 
    

提交回复
热议问题