首页 > 解决方案 > 以编程方式更改为 SwiftUI 中的另一个选项卡

问题描述

我正在尝试在 SwiftUI 中实现,您在一个选项卡上的视图中按下一个按钮,它会更改为另一个选项卡。我会使用 UIKit:

if [condition...button pressed] {
    self.tabBarController!.selectedIndex = 2
}

但是在 SwiftUI 中是否有等效的方法来实现这一点?

标签: iosswiftswiftui

解决方案


您只需要更新@State负责选择的变量。但是,如果您想从子视图中执行此操作,则可以将其作为@Binding变量传递:

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")
        }
    }
}

推荐阅读