Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why onAppear called again after onDisappear while switching tab in TabView in SwiftUI?

I am calling API when tab item is appeared if there is any changes. Why onAppear called after called onDisappear?

Here is the simple example :

struct ContentView: View {
    var body: some View {
        TabView {
            NavigationView {
                Text("Home")
                    .navigationTitle("Home")
                    .onAppear {
                        print("Home appeared")
                    }
                    .onDisappear {
                        print("Home disappeared")
                    }
            }
            .tabItem {
                Image(systemName: "house")
                Text("Home")
            }.tag(0)
        
            NavigationView {
                Text("Account")
                    .navigationTitle("Account")
                    .onAppear {
                        print("Account appeared")
                    }
                    .onDisappear {
                        print("Account disappeared")
                    }
            }
            .tabItem {
                Image(systemName: "gear")
                Text("Account")
            }.tag(1)
        }
    }
}    

Just run above code and we will see onAppear after onDisappear.

Home appeared
---After switch tab to Account---
Home disappeared
Account appeared
Home appeared

Is there any solution to avoid this?

like image 688
Jay Patel Avatar asked Aug 04 '20 17:08

Jay Patel


People also ask

How do I change the TabView color in SwiftUI?

To change the background color and default tab item colors, some extra work is required as demonstrated below. As shown in lines 2-4, we can use UITabBar. appearance(). backgroundColor to modify the color of the tab bar.

How do I hide the tab bar in SwiftUI?

If we want to hide the TabBar , we just write TabView into NavigationView , making the NavigationView the super-view and the TabView the child-view, which is just opposite to the above View Hierarchy .

How do I add a tab bar in SwiftUI?

Press Cmd+N to create a new SwiftUI View, calling it “MainView”. Creating tabs is as easy as putting different views inside an instance of TabView , but in order to add an image and text to the tab bar item of each view we need to use the tabItem() modifier.


1 Answers

To whom it may help.

Because this behaviour I only could reproduce on iOS 14+, I end up using https://github.com/NicholasBellucci/StatefulTabView (which properly only get called when showed; but don't know if it's a bug or not, but it works with version 0.1.8) and TabView on iOS 13+.

like image 117
Fx. Avatar answered Sep 22 '22 11:09

Fx.