以编程方式更改到 SwiftUI 中的另一个选项卡

问题描述 投票:0回答:2

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

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

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

ios swift swiftui
2个回答
74
投票

您只需要更新负责选择的

@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 {
            tabSelection = 2
        } label: {
            Text("Change to tab 2")
        }
    }
}

3
投票

如果您想从更深层次的视图切换,您可能喜欢使用@AppStorage或@SceenStorage来保存选定的选项卡。

可能看起来像:

@SceneStorage("selectedView") var selectedView: String?
    
    var body: some View {
        TabView (selection: $selectedView){
            NavigationView {
                TimerView()
            }
            .tag(TimerView.tag)
            .tabItem {
                Image(systemName: "stopwatch.fill")
                Text("Timer")
            }...

然后在更深入的视图中的任何地方:

 Button(action: {
                selectedView = TimerView.tag
                    }) {
                        Text("Switch Tab")
                      
                    }

示例中的 TimerView.tag 只是常量,不跨应用程序使用字符串:

static let tag: String? = "Timer"

一旦您更新 @SceneStorage 值,SwiftUI 将负责选项卡切换,并且它也会保存应用程序中最后打开的选项卡。

© www.soinside.com 2019 - 2024. All rights reserved.