3

I'm trying to implement a feature to an app I'm working on so that when a user taps a tab twice, it will automatically send the user back to the tab's initial view.

Suppose that I want the following "Devices" tab button to reload the view on a double tap:

enter image description here

This is the code I've been trying to use to solve this issue:

Tab View {
         DevicesScreen()
             .tabItem {
                 Image(systemName: "tv")
                 Text("Devices")
             }.onTapGesture(count: 2) {
                 DevicesScreen()
         }
}.font(.headline)

However, the result of the onTapGesture won't switch the view, therefore I wanted to ask whether there is another solution to the problem.

Thanks in advance.

RnadomG
  • 145
  • 1
  • 9
  • Does this answer your question https://stackoverflow.com/a/60691250/12299030? – Asperi Sep 18 '20 at 12:40
  • @Asperi It doesn't really give me the behaviour I'm looking for since I want the user to be able to double-tap the current tab (from within a sub-view of the current tab view) and get the "source" view of the tab but thanks for the answer – RnadomG Sep 18 '20 at 14:37
  • What do you mean by sub view? In NavigationView? Would you prepare minimal reproducible demo of use-case? – Asperi Sep 18 '20 at 15:51
  • Ah, I ended up using a HStack of buttons instead of a tab view to get the wanted result and it worked, thanks though. – RnadomG Sep 20 '20 at 14:06

1 Answers1

1

try this:

struct ContentView: View {
    
    @State var selectedTab: Tab = .home
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Home Screen")
                .tabItem { Text("Home") }
                .tag(Tab.home)
            Text("More Screen")
                .tabItem { Text("More") }
                .tag(Tab.more)
            
            Text("bla Screen")
                .tabItem { Text("bla") }
                .tag(Tab.bla)
            
        }.onTapGesture(count: 2) {
            if self.selectedTab == .more {
                self.selectedTab = .home
            }
        }
    }
}

extension ContentView {
    enum Tab: Hashable {
        case home
        case more
        case bla
    }
}
Chris
  • 7,579
  • 3
  • 18
  • 38
  • I think, RnadomG just wanted to popToRoot controller of current TAB(Devices). – Saurabh Prajapati Sep 18 '20 at 12:02
  • I have a view that calls a sub-view from within it and I'd like to get back to the original view when double-tapping the tab so what you're purposing isn't really solving the problem but thanks for the answer – RnadomG Sep 18 '20 at 14:24
  • 1
    The problem with this is onTapGesture is executed also on tap of background of the main view – Dharay Mar 23 '21 at 05:42