SwiftUI - ScrollViewReader 的 scrollTo 不滚动

mah*_*han 4 scrollview ios swift swiftui

我有一个简单的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()
    }
}
Run Code Online (Sandbox Code Playgroud)

我在模拟器和物理设备上在 iOS 14.2 上对其进行了测试。

我阅读了它的文档,但没有太多信息。那么如何滚动到一行,例如第 50 行?

mah*_*han 13

ScrollViewReader仅适用于:

  • 显式使用ScrollView
  • 可识别集合列表

除非您明确设置 id,否则它不适用于 List of Range<Int>

显式设置 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)
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Har*_*tel 5

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)
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)