【问题标题】:SwiftUI - ScrollViewReader's scrollTo does not scrollSwiftUI - ScrollViewReader 的 scrollTo 不滚动
【发布时间】:2021-03-06 16:00:24
【问题描述】:

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

【问题讨论】:

  • 嗯...适用于 iOS 14.1。我观察到在 14.2 SwiftUI 中报告了太多缺陷...

标签: ios swift swiftui scrollview


【解决方案1】:

ScrollViewReader 仅适用于:

  • 明确使用ScrollView
  • 可识别收藏列表

它不适用于List 或Range&amp;lt;Int&gt;,除非您明确设置它的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)
                    }
                }
            }
        }
    }
}

【讨论】:

    【解决方案2】:
    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)
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2022-10-17
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多