Programmatically change to another tab in SwiftUI

左心房为你撑大大i 提交于 2021-01-27 07:54:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!