问题
I'm trying to implement in SwiftUI where you press a button in a view on one tab, it changes to another tab. I would do with UIKit:
if [condition...button pressed] {
self.tabBarController!.selectedIndex = 2
}
But is there an equivalent way to achieve this in SwiftUI?
回答1:
You just need to update a @State variable responsible for the selection. But if you want to do it from a child View you can pass it as a @Binding variable:
struct ContentView: View {
@State private var tabSelection = 1
var body: some View {
TabView(selection: $tabSelection) {
FirstView(tabSelection: $tabSelection)
.tabItem {
Text("Tab 1")
}
.tag(1)
Text("tab 2")
.tabItem {
Text("Tab 2")
}
.tag(2)
}
}
}
struct FirstView: View {
@Binding var tabSelection: Int
var body: some View {
Button(action: {
self.tabSelection = 2
}) {
Text("Change to tab 2")
}
}
}
来源:https://stackoverflow.com/questions/62504400/programmatically-change-to-another-tab-in-swiftui