最简单的方法是包在里面
ScrollViewReader
和改变
ForEach
按索引遍历数组。我制作了一个数组,用0…200范围内的数字模拟,并创建了一个按钮滚动到索引120处的元素。
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack {
Button {
withAnimation {
proxy.scrollTo(120, anchor: .center)
}
} label: {
Text("Scroll")
}
ZStack {
Color.blue
LazyVGrid(
columns: columns,
alignment: .center,
spacing: 10,
pinnedViews: []
) {
//Iterating by index
ForEach(0..<items.count, id: \.self) { i in
Text(items[i].title)
.listRowBackground(Color.clear)
.id(i) //<- put index here
.padding(.horizontal, 15)
}
}
.listStyle(PlainListStyle())
}
}
}
}
}
输出: