像大多数iOS应用一样,在SwiftUI中,是否可以通过点击选项卡栏弹出到根视图?
这是预期行为的example。
我尝试使用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")
}
}
但是似乎这些手势被忽略了。
任何建议或解决方案都将受到赞赏
答案 0 :(得分:2)
我们可以使用标签栏选择绑定来获取选中的索引。在此绑定上,我们可以检查选项卡是否已被选中,然后弹出到根目录以进行选择导航。
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")
}
}
答案 1 :(得分:0)
您可以通过将 TabView 放在 NavigationView 中来实现这一点,如下所示:
struct ContentView: View {
@State var selection = 0
var body: some View {
NavigationView {
TabView(selection: $selection) {
FirstTabView()
.tabItem {
Label("Home", systemImage: "house")
}
.tag(0)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct FirstTabView: View {
var body: some View {
NavigationLink("SecondView Link", destination: SecondView())
}
}
struct SecondView: View {
var body: some View {
Text("Second View")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ContentView()
}
}
}