我目前正在使用SwiftUI开发应用程序。
此应用有2个视图,可控制一个标签视图。
我想获取有关在TabView中选择哪个视图的值。
有什么办法吗?
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
FirstView()
.tabItem {
Text("First")
}.tag(1)
SecondView()
.tabItem {
Text("Second")
}.tag(2)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
FirstView.swift
import SwiftUI
struct FirstView: View {
var body: some View {
Text("FirstView")
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift
import SwiftUI
struct SecondView: View {
var body: some View {
Text("SecondView")
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
Xcode:版本11.7
Swift:Swift 5
答案 0 :(得分:1)
您需要使用选择内容,如下所示
注意:选择内容应与标签所用的类型相同(并使用标签中的相应值以编程方式选择特定标签)
struct ContentView: View {
@State private var selectedTab = 1 // default selection
var body: some View {
TabView(selection: $selectedTab) { // << here !!
FirstView()
.tabItem {
Text("First")
}.tag(1)
SecondView()
.tabItem {
Text("Second")
}.tag(2)
}
}
}