如何在点击按钮时以编程方式切换选项卡?在swiftui [英] how to switch tab programmatically on button click? in swiftui
本文介绍了如何在点击按钮时以编程方式切换选项卡?在swiftui的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在代码中实现了标签栏.我在第一个选项卡中看到了所有按钮,我想以编程方式从该按钮切换到第二个选项卡.当我使用navigationView时,它将创建另一个标签栏并移至该屏幕,这将改变swiftui中的导航索引.
I have implemented tab bar in my code. I have see all button in my first tab and from that button i want to switch to second tab programmatically. When I use navigationView then it creates another tab bar and moves to that screen and this changes the index of navigation in swiftui.
struct AppTabNavigation: View {
@State var selection: Tab = .dashboard
var body: some View {
TabView(selection: $selection) {
NavigationView {
FirstTabView()
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Label("Home", systemImage: "house.fill")
.accessibility(label: Text("Home"))
}
.tag(Tab.home)
NavigationView {
SecondView()
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Label("Home", systemImage: "house.fill")
.accessibility(label: Text("Home"))
}
.tag(second)
}
}
}
导航代码:
NavigationLink(destination: AppTabNavigation(selection: Tab.home), isActive: self.$isActiveTabbar){
Text("")
} .isDetailLink(false)
推荐答案
以下是一种可能的方法演示-想法是将带有选项卡选择的绑定移动到带有按钮的视图中,以便按钮动作可以更改它.
Here is a demo of possible approach - the idea is to move binding for tab selection into view with buttons, so button action could change it.
通过Xcode 12/iOS 14测试
Tested with Xcode 12 / iOS 14
enum Tab {
case dashboard
case home
case second
}
struct AppTabNavigation: View {
@State var selection: Tab = .home
var body: some View {
TabView(selection: $selection) {
NavigationView {
FirstTabView(tab: $selection)
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Label("Home", systemImage: "house.fill")
.accessibility(label: Text("Home"))
}
.tag(Tab.home)
NavigationView {
Text("SecondView")
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Label("Home", systemImage: "house.fill")
.accessibility(label: Text("Home"))
}
.tag(Tab.second)
}
}
}
struct FirstTabView: View {
@Binding var tab: Tab
var body: some View {
Button("Go Second") { self.tab = .second }
}
}
这篇关于如何在点击按钮时以编程方式切换选项卡?在swiftui的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文