swiftUI ScrollView怎么自动翻到指定位子
时间: 2023-09-13 20:04:33 浏览: 43
在SwiftUI中,我们可以使用ScrollView的scrollTo方法来将滚动视图自动滚动到指定的位置。使用scrollTo方法需要指定要滚动到的位置,这个位置可以是某个具体的视图,也可以是某个偏移量。
下面是一个示例代码,用于将ScrollView自动滚动到指定位置:
```swift
struct ContentView: View {
let itemCount = 20 // 列表项数量
@State var selectedItem: Int? // 当前选中的列表项
var body: some View {
ScrollView {
VStack(spacing: 20) {
ForEach(0..<itemCount) { index in
Button("Item \(index+1)") {
selectedItem = index // 点击时选中该列表项
scrollToSelected() // 滚动到选中的列表项
}
.frame(maxWidth: .infinity, maxHeight: 50)
.background(selectedItem == index ? Color.blue : Color.gray)
.foregroundColor(.white)
}
}
.padding()
}
}
func scrollToSelected() {
withAnimation {
guard let selectedItem = selectedItem else { return }
let selectedRect = CGRect(x: 0, y: CGFloat(selectedItem) * 70, width: 1, height: 1) // 计算选中项的位置
ScrollViewReader { scrollView in
scrollView.scrollTo(selectedRect, anchor: .top) // 滚动到选中项
}
}
}
}
```
在这个示例代码中,我们首先创建了一个包含多个按钮的ScrollView,并且使用一个状态变量selectedItem来记录当前选中的列表项。当用户点击某个列表项时,我们会将selectedItem设置为该项的索引,并且调用scrollToSelected方法来将ScrollView自动滚动到选中的列表项。
在scrollToSelected方法中,我们首先使用withAnimation修饰符来启用动画效果。然后,我们根据选中项的索引计算出该项的位置,创建一个CGRect对象,然后使用ScrollViewReader和scrollTo方法来将ScrollView滚动到该位置。
需要注意的是,scrollTo方法需要在ScrollViewReader的闭包中调用,因为只有在该闭包中才能访问到ScrollView的实例。此外,需要指定anchor参数来指定滚动位置的对齐方式,这里我们使用了.top来将选中项的顶部对齐到ScrollView的顶部。