如何在 swiftUI 中切换到另一个 TabView?

时间:2021-04-01 11:49:39

标签: swift swiftui

我知道以前有人问过这个问题,我找到了其中的一些,但我的略有不同。

我发现这个例子:

Programmatically change to another tab in SwiftUI

如果您在同一个 Swift 文件中拥有 struct ContentView: View {...}struct FirstView: View {...},这可以正常工作。

但在我的项目中,我在 1 个 Swift 文件中有 struct ContentView: View {...},在另一个单独的 Swift 文件中有 struct FirstView: View {...}

因此,当我在 @Binding var tabSelection: Int 文件中使用 FirstView() 时,我的 ContentView 文件中出现此错误:Argument passed to call that takes no arguments

有人可以就这个问题提出建议吗?

1 个答案:

答案 0 :(得分:1)

例如,如果您尝试此示例,它将起作用!如果你把它们放在不同的文件中,它根本不会对结果产生任何影响!

文件内容视图:

import SwiftUI

struct ContentView: View {
    @State private var tabSelection = 1
    
    var body: some View {
        TabView(selection: $tabSelection) {
            
            FirstView(tabSelection: $tabSelection)
                .tabItem {
                    Text("Tab 1")
                }
                .tag(1)
            
            SecondView(tabSelection: $tabSelection)
                .tabItem {
                    Text("Tab 2")
                }
                .tag(2)
        }
    }
}

文件第一视图:

import SwiftUI

struct FirstView: View {
    
    @Binding var tabSelection: Int
    
    var body: some View {
        
        Button(action: { tabSelection = 2 }) { Text("Change to tab 2") }
        
    }
}

文件第二视图:

import SwiftUI

struct SecondView: View {
    
    @Binding var tabSelection: Int
    
    var body: some View {
        
        Button(action: { tabSelection = 1 }) { Text("Change to tab 1") }
        
    }
}