首页 > 解决方案 > 在 SwiftUI 中使用 Tab Bar 弹出到根视图

问题描述

在 SwiftUI 中,有什么方法可以像大多数 iOS 应用程序一样通过点击 Tab Bar 来弹出到根视图?

这是预期行为的示例

在此处输入图像描述

我尝试使用simultaneousGesture以下方式以编程方式弹出视图:

import SwiftUI


struct TabbedView: View {
    @State var selection = 0
    @Environment(\.presentationMode) var presentationMode
    var body: some View {
                TabView(selection: $selection) {
            RootView()
                .tabItem {
                    Image(systemName: "house")
                    .simultaneousGesture(TapGesture().onEnded{
                        self.presentationMode.wrappedValue.dismiss()
                        print("View popped")
                    })
            }.tag(0)
                
            Text("")
                .tabItem {
                    Image(systemName: "line.horizontal.3")
            }.tag(1)
        }
    }
}

struct RootView: View {
    var body: some View{
        NavigationView{
            NavigationLink(destination:SecondView()){
        Text("Go to second view")
            }
        }
    }
}

struct SecondView: View {
    var body: some View{
        Text("Tapping the house icon should pop back to root view")
    }
}

但似乎这些手势被忽略了。

非常感谢任何建议或解决方案

标签: swiftswiftui

解决方案


我们可以使用标签栏选择绑定来获取选中的索引。在此绑定上,我们可以检查选项卡是否已被选中,然后弹出到根目录进行选择导航。

struct ContentView: View {

@State var showingDetail = false
@State var selectedIndex:Int = 0

var selectionBinding: Binding<Int> { Binding(
    get: {
        self.selectedIndex
    },
    set: {
        if $0 == self.selectedIndex && $0 == 0 && showingDetail {
            print("Pop to root view for first tab!!")
            showingDetail = false
        }
        self.selectedIndex = $0
    }
)}

var body: some View {
    
    TabView(selection:selectionBinding) {
        NavigationView {
            VStack {
                Text("First View")
                NavigationLink(destination: DetailView(), isActive: $showingDetail) {
                    Text("Go to detail")
                }
            }
        }
        .tabItem { Text("First") }.tag(0)
        
        Text("Second View")
            .tabItem { Text("Second") }.tag(1)
    }
  }
}

struct DetailView: View {
 var body: some View {
    Text("Detail")
  }
}

推荐阅读