I've implemented TabView with 2 tabs and possibility to popToRootView. But now i wonder if it's possible to somehow open last visited View if i tap on unselected tab ? What i mean: I have tab1 and tab2
- User tap on tab1 and see RootView of tab1, the goes to ViewA and goes next to ViewB.
- Then he taps on tab2 and when he taps back to tab1 he sees RootView of tab 1
But how can send him to ViewB not RootView of tab 1
I go to Choose category -> Choose level -> Choose lesson and I change the tab to Profile. Then I change the tab to Home and I’m taken to the root but could i keep the user on the Choose lesson screen when they switch from another tab? In order words - can we make “pop to root view controller” work only when the currently selected tab is the Home one?
TabView:
struct ContentView: View {
@StateObject var tabState = TabState()
var body: some View {
TabView(selection: $tabState.selectedTab) {
NavigationView {
if (UserDefaults.standard.value(forKey: "onboardingShown") as? Bool) == true {
NavigationLink(destination: ContentView(), isActive: $tabState.showTabRoots[0]) {
LogInScreen()
}
} else {
OnboardingScreen()
}
}
.onAppear(perform: {
tabState.lastSelectedTab = TabState.Tab.first
}).tabItem {
Label("Головна", image: "home-selected")
}.tag(TabState.Tab.first)
NavigationView {
NavigationLink(destination: AccountScreen(), isActive: $tabState.showTabRoots[1]) {
Text("Hello World!")
}
}
.onAppear(perform: {
tabState.lastSelectedTab = TabState.Tab.second
}).tabItem {
Label("Профайл", image: "account-selected")
}.tag(TabState.Tab.second)
}
.onReceive(tabState.$selectedTab) { selection in
if selection == tabState.lastSelectedTab {
tabState.showTabRoots[selection.rawValue] = false
}
}
}
}
TabState:
class TabState: ObservableObject {
enum Tab: Int, CaseIterable {
case first = 0
case second = 1
case third = 2
case fourth = 3
}
@Published var selectedTab: Tab = .first
@Published var lastSelectedTab: Tab = .first
@Published var showTabRoots = Tab.allCases.map { _ in
false
}
}