SwiftUI - ScrollViewReader#39;s scrollTo does not scroll(SwiftUI-ScrollViewReader的ScrollTo不滚动)
问题描述
我有一个简单的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上分别在模拟器和物理设备上进行了测试。
我读了它的documentation,但信息不多。那么如何滚动到一行,例如第50行呢?
推荐答案
ScrollViewReader
仅适用于:
- 显式使用
ScrollView
- 可识别集合列表
它不能与Range<Int>
的List
一起使用,除非您显式设置其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)
}
}
}
}
}
}
这篇关于SwiftUI-ScrollViewReader的ScrollTo不滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!