如何停止其他标签的偏移量影响标签的滚动视图的偏移量?
我不想每次显示新标签时都将滚动视图强制移到顶部,而只是希望新标签不受我上次查看的标签滚动位置的影响。
import SwiftUI
enum Tab {
case First, Second, Third
var title: String {
switch self {
case .First:
return "First"
case .Second:
return "Second"
case .Third:
return "Third"
}
}
}
struct ContentView: View {
@State var selectedTab = Tab.First
var body: some View {
NavigationView {
TabView(selection: $selectedTab) {
FirstView()
.tabItem {
Text("First")
}.tag(Tab.First)
SecondView()
.tabItem {
Text("Second")
}.tag(Tab.Second)
ThirdView()
.tabItem {
Text("Third")
}.tag(Tab.Third)
}.navigationBarTitle(selectedTab.title, displayMode: .automatic)
.navigationBarHidden(false)
}
}
}
struct FirstView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
struct SecondView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
struct ThirdView: View {
let data = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
ScrollView(showsIndicators: true) {
VStack {
ForEach(data, id: \.self) { item in
Text("\(item)")
.frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: .infinity, alignment: .center)
}
}
}
}
}
答案 0 :(得分:2)
这是因为您使用一个NavigationView
,所以它保留了自己的状态。为每个标签设置NavigationView
独立。
通过Xcode 12 / iOS 14测试
struct ContentView: View {
@State var selectedTab = Tab.First
var body: some View {
TabView(selection: $selectedTab) {
NavigationView {
FirstView()
.navigationBarTitle(Tab.First.title)
}
.tabItem {
Text("First")
}.tag(Tab.First)
NavigationView {
SecondView()
.navigationBarTitle(Tab.Second.title)
}
.tabItem {
Text("Second")
}.tag(Tab.Second)
NavigationView {
ThirdView()
.navigationBarTitle(Tab.Third.title)
}
.tabItem {
Text("Third")
}.tag(Tab.Third)
}
}
}