我有一组years和一个selected year。我想要的是每当我的视图加载时,它应该自动移动到 selected year.
这是我的代码:
struct Testing: View {
let years = ["2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026"]
@State var selectedYear = "2023"
@Namespace private var animation
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 20) {
ForEach(years.indices, id: \.self) { index in
Button {
withAnimation(.linear(duration: 0.5)) {
selectedYear = years[index]
}
} label: {
VStack {
Text("\(years[index])")
.foregroundColor(.white)
.fontWeight(.semibold)
.padding(.horizontal, 15)
if selectedYear == years[index] {
Capsule()
.fill(.white)
.frame(height: 5)
.padding(.horizontal, -5)
}
}
}
}
}.padding().background {
Rectangle()
.fill(Color.purple)
}
}
}
}
这回来了
每当加载视图时,它应该在中间显示 selectedYear。我怎样才能做到这一点?
您可以使用
ScrollViewReader
容器视图,它提供了一种机制来读取滚动视图的内容偏移量并使用scrollTo
方法滚动到其中的特定材料。
这是更新的代码:
struct Testing: View {
let years = ["2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026"]
@State var selectedYear = "2023"
@Namespace private var animation
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader { scrollView in // --> Here
HStack(spacing: 20) {
ForEach(years.indices, id: \.self) { index in
Button {
withAnimation(.linear(duration: 0.5)) {
selectedYear = years[index]
}
} label: {
VStack {
Text("\(years[index])")
.foregroundColor(.white)
.fontWeight(.semibold)
.padding(.horizontal, 15)
if selectedYear == years[index] {
Capsule()
.fill(.white)
.frame(height: 5)
.padding(.horizontal, -5)
}
}
.id(years[index]) // ---> Here
}
}
}
.padding().background {
Rectangle()
.fill(Color.purple)
}
.onAppear {
scrollView.scrollTo(selectedYear, anchor: .center) // ---> Here
}
}
}
}
}