swift - 在 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")
}
}
但似乎这些手势被忽略了。
非常感谢任何建议或解决方案
解决方案
我们可以使用标签栏选择绑定来获取选中的索引。在此绑定上,我们可以检查选项卡是否已被选中,然后弹出到根目录进行选择导航。
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")
}
}
推荐阅读
- kubernetes - 用本地机器中文件的值覆盖 GKE 上部署的 Helm-chart 值?
- macos - Mac 开发者的隐私是否得到保障?
- google-chrome - 铬轮廓仪火焰图表中的大间隙
- arduino - 电线插头激活 Arduino 报警器
- javascript - 如何使以数字开头的电子邮件在 RTL 上而不是 test-mail.com@000 上正确显示?
- unix - gnu并行管道sed - 没有输入文件错误
- azure - 将数据从本地 SQL 服务器复制和整合到 Azure Blob
- powershell - 基于另一个参数的已指定值,制表符完成一个参数值
- pandas - Pandas Dictionary:如何通过将输入值与分配给单个键的多个值匹配来返回键
- javascript - 使用 Ajax 的按钮在 Django 项目中不起作用