在 SwiftUI 中使用选项卡栏弹出到根视图

2024-01-07

在 SwiftUI 中,有没有办法像大多数 iOS 应用程序一样通过点击选项卡栏来弹出到根视图?

这是一个example https://i.stack.imgur.com/RBEvL.gif的预期行为。

我尝试使用以编程方式弹出视图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")
    }
}

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

任何建议或解决方案将不胜感激


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

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")
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 SwiftUI 中使用选项卡栏弹出到根视图 的相关文章

随机推荐