【问题标题】:How to switch to another TabView in swiftUI? [duplicate]如何在 swiftUI 中切换到另一个 TabView? [复制]
【发布时间】:2021-04-01 20:03:19
【问题描述】:

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

我发现了这个例子:

Programmatically change to another tab in SwiftUI

如果您在同一个 Swift 文件中拥有 struct ContentView: View {...}struct FirstView: View {...},则效果很好。

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

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

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

【问题讨论】:

  • 它根本不会对结果产生任何影响,你可能在另一个问题上运行!你能展示你真实使用的代码吗?
  • @swiftPunk,它的代码很大。让我看看我能不能把它缩小。

标签: swift swiftui


【解决方案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") }
        
    }
}

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 2021-10-17
    • 2022-12-19
    • 2020-02-19
    • 2022-11-05
    • 2022-01-20
    • 1970-01-01
    • 2017-12-19
    • 2020-03-12
    相关资源
    最近更新 更多