我有一个可滚动的选项卡视图,单击主视图(ContentView)中的任一按钮即可显示。我希望在单击“视图 1”时显示第一个选项卡,在单击“视图 2”时显示第二个选项卡。打开选项卡视图后,它应该仍然可以正常工作,这意味着选项卡按钮和滚动仍然可以正常工作。现在我想了一下,这类似于点击 Instagram 上的“关注者”或“关注”按钮。
当我单击“视图 2”时,它会正确显示第二个选项卡,但是当我单击“视图 1”的选项卡按钮时,屏幕不会显示视图 1 文本。 。有谁知道如何修复这个错误?谢谢!
ContentView.swift:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
HStack {
NavigationLink {
ScrollTab(currentTab: 0)
} label: {
Text("View 1")
.font(.subheadline)
.fontWeight(.semibold)
}
NavigationLink {
ScrollTab(currentTab: 1)
} label: {
VStack {
Text("View 2")
.font(.subheadline)
.fontWeight(.semibold)
}
.frame(width: 76)
}
}
}
}
}
ScrollTab.swift:
struct ScrollTab: View {
@State private var currentTab: Int = 0
init(currentTab: Int) {
_currentTab = State(initialValue: currentTab)
}
var body: some View {
Spacer()
VStack(alignment: .center, spacing: 0) {
TabBarView(currentTab: self.$currentTab)
TabView(selection: self.$currentTab) {
Text("This is view 1").tag(0)
.onAppear() {
self.currentTab = 0
}
Text("This is view 2").tag(1)
.onAppear() {
self.currentTab = 1
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
.background(Color.secondary)
}
.edgesIgnoringSafeArea(.all)
}
}
struct TabBarView: View {
@Binding var currentTab: Int
@Namespace var namespace
var tabBarOptions: [String] = ["View 1", "View 2"]
var body: some View {
HStack(spacing: 20) {
ForEach(Array(zip(self.tabBarOptions.indices,
self.tabBarOptions)),
id: \.0,
content: {
index, name in
TabBarItem(currentTab: self.$currentTab,
namespace: namespace.self,
tabBarItemName: name,
tab: index)
})
}
.padding(.horizontal)
.background(Color.orange) // <<<< Remove
.frame(height: 80)
}
}
struct TabBarItem: View {
@Binding var currentTab: Int
let namespace: Namespace.ID
var tabBarItemName: String
var tab: Int
var body: some View {
Button {
self.currentTab = tab
} label: {
VStack {
Spacer()
Text(tabBarItemName)
if currentTab == tab {
Color.black
.frame(height: 2)
.matchedGeometryEffect(id: "underline",
in: namespace,
properties: .frame)
} else {
Color.clear.frame(height: 2)
}
}
.animation(.spring(), value: self.currentTab)
}
.buttonStyle(.plain)
}
}
正如我在上面的评论中所说,在 TabView(selection: self.$currentTab) 行下,您有两个带有 onAppear 的文本视图。这就是出现问题的地方。
因此,我将这两个视图与 ScrollTab 视图分开,并创建了另一个名为 TextView 的视图,如下所示。
import SwiftUI
struct ScrollTab: View {
@State private var currentTab: Int = 0
init(currentTab: Int) {
_currentTab = State(initialValue: currentTab)
}
var body: some View {
Spacer()
VStack(alignment: .center, spacing: 0) {
TabBarView(currentTab: self.$currentTab)
TabView(selection: self.$currentTab) {
TextView(currentTab: $currentTab)
}
.tabViewStyle(.page(indexDisplayMode: .never))
.background(Color.secondary)
}
.edgesIgnoringSafeArea(.all)
}
}
#Preview {
ScrollTab(currentTab: 1)
}
struct TextView: View {
@Binding var currentTab: Int
var body: some View {
VStack {
if currentTab == 0 {
Text("This is view 1")
} else {
Text("This is view 2")
}
}
}
}
我没有接触过ContentView和其他actor。