1

I have List with 100 items I want to scroll to item number 20 How can I achieve this in SwiftUI

Here is my simple ListCode

struct ContentView: View {
    var body: some View {
        List {
            Button(action: {
                self.scrollToIndex(index: 20)
            }) {
                Text("Scroll To 20")
            }
            ForEach(0..<100) {_ in
                Text("Hello World")
            }
        }
    }

    func scrollToIndex(index: Int) {

    }
}
Kishore Suthar
  • 2,943
  • 4
  • 26
  • 44

2 Answers2

0

Earlier tried to find some solutions for this answering here. Shortly: today (November 2019) I found no solutions, except using ScrollView or UITableView (making last UIViewControllerRepresentable)

update found Apple Developer Forums thread with this question from September and there is still no answer

Hrabovskyi Oleksandr
  • 3,070
  • 2
  • 17
  • 36
0

With the new ScrollViewReader in iOS 14, you can simply do something like that:

struct ContentView: View {
    var body: some View {
        ScrollViewReader { proxy in
            List {
                Button(action: {
                    self.scrollToIndex(proxy, index: 20)
                }) {
                    Text("Scroll To 20")
                }
                ForEach(0..<100) { i in
                    Text("Hello World").id(i)
                }
            }
        }
    }

    func scrollToIndex(_ proxy: ScrollViewProxy, index: Int) {
        withAnimation {
            proxy.scrollTo(index)
        }
    }
}
Kai Zheng
  • 6,640
  • 7
  • 43
  • 66