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

roo*_*far 1 swift swiftui

我知道这个问题以前曾被问过,我发现了其中一些,但我的略有不同。

我发现这个例如:

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

如果你在同一个 Swift 文件上有struct ContentView: View {...}和,那么它就可以正常工作。struct FirstView: View {...}

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

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

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

use*_*ser 6

例如,如果您尝试这个示例,它就会起作用!如果你把它们放在不同的文件中,结果根本不会有任何差异!

文件内容查看:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

文件第一视图:

import SwiftUI

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

文件第二次查看:

import SwiftUI

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