以编程方式更改为SwiftUI中的另一个选项卡 [英] Programmatically change to another tab in SwiftUI

查看:67
本文介绍了以编程方式更改为SwiftUI中的另一个选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在SwiftUI中实现,您可以在其中一个选项卡上的视图中按一个按钮,然后将其更改为另一个选项卡.我会使用UIKit:

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
}

但是有没有等效的方法可以在SwiftUI中实现这一目标?

But is there an equivalent way to achieve this in SwiftUI?

推荐答案

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

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

这篇关于以编程方式更改为SwiftUI中的另一个选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆