我有一个简单的 SwiftUI 列表,当用户单击按钮时我想滚动到一行。我从 hackingwithswift 复制了这段代码。它应该起作用,但它不起作用。
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(5, anchor: .top)
}
List(0..<100) { i in
Text("Example \(i)")
.id(i)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我在 iOS 14.2 上在模拟器和物理设备上进行了测试。
我阅读了它的文档,但没有太多信息。那么如何滚动到某一行,例如第50行?
ScrollViewReader
仅适用于:
ScrollView
除非您明确设置其
List
,否则它不适用于 Range<Int>
的 id
。
显式设置 id。
// List(0..<100, id: \.self)
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(5, anchor: .top)
}
List(0..<100, id: \.self) { i in
Text("Example \(i)")
.id(i)
}
}
}
}
}
// ForEach(0..<50000, id: \.self)
struct ContentView: View {
var body: some View {
ScrollView {
ScrollViewReader { proxy in
LazyVStack {
ForEach(0..<50000, id: \.self) { i in
Button("Jump to \(i+500)") {
proxy.scrollTo(i+500, anchor: .top)
}
Text("Example \(i)")
.id(i)
}
}
}
}
}
}
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(50, anchor: .top)
}
List{
ForEach(0..<100) { i in
Text("Example \(i)")
.id(i)
}
}
}
}
}
}