I have a very basic setup which involves NavigationView
s inside a TabView
. Within that NavigationView
, users can go to other screens.
I would expect, like in other every app I have seen, is that when I tap on the current active tab, it jumps back to the initial NavigationView
, dismissing all other NavigationView
s active in that tab. However, when I press on the active tab, nothing happens.
Is there a property I must set to make this work?
CodePudding user response:
What you describe it not a standard SwiftUI behavior, and to make it worse you cannot detect the second tap on a TabBar icon. The only way I know is to use a custom TabBar setup, e.g. like this:
struct ContentView: View {
@State private var currentTab = "Analytics"
var body: some View {
VStack {
TabView(selection: $currentTab) {
VStack {
Text("Home Tab")
}
.tag("Home")
VStack {
Text("Analytics Tab")
}
.tag("Analytics")
}
Divider()
HStack {
TabBarButton(imageName: "house.fill", label: "Home", current: $currentTab)
TabBarButton(imageName: "chart.bar.fill", label: "Analytics", current: $currentTab)
}
}
}
}
struct TabBarButton: View {
let imageName: String
let label: String
@Binding var current: String
var body: some View {
Button {
if current == label {
// reset your view
print("reset")
}
current = label
} label: {
VStack {
Image(systemName: imageName)
Text(label)
}
}
.padding()
}
}