SwiftUI - ScrollViewReader 的 scrollTo 不滚动

SwiftUI - ScrollViewReader's scrollTo does not scroll

我有一个简单的 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行?

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)
                    }
                }
            }
        }
    }
}

ScrollViewReader 仅适用于:

  • 显式使用 ScrollView
  • 可识别列表collection

除非您明确设置其 id,否则它不适用于 Range&lt;Int>List

明确设置 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)
                    }
                }
            }
        }
    }
}