avatar
Published on

How to make a SwiftUI List scroll automatically?

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @0x7fs

When you have a List or ScrollView in SwiftUI and you want to scroll to a specific item automatically, you can use the ScrollViewReader and ScrollViewProxy to achieve this. Wrap your ScrollView in a ScrollViewReader and access the proxy provided to its content closure. As long as your list elements are Hashable, you can simple tell the proxy which element to scroll to.

struct ContentView: View {
    @State private var colors: [Color] = [
        .red, .orange, .yellow, .green, .blue, .indigo, .purple
    ]

    var body: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack {
                    Button("Scroll to bottom") {
                        withAnimation {
                            proxy.scrollTo(colors[colors.endIndex - 1])
                        }
                    }

                    ForEach(colors, id: \.self) { color in
                        color.frame(
                            height: 200
                        )
                    }
                }
            }
        }
    }
}

You can optionally provide the scrollTo method with an anchor to specify where the item should be positioned after scrolling.

proxy.scrollTo(colors[colors.endIndex - 1], anchor: .center)