4

I'm trying to make the scroll reset to the top of the page when a view appears (e.g. when you navigate back from a navigation link). The ScrollView is embedded within a NavigationView with a large title.

Using the code below, I'm able to reset the scroll to the first element on the page using ScrollViewReader and scrollTo.

However, I'd like for the view to scroll all the way to the top such that the large navigation bar title reappears. Instead, I just see the inline title.

Is there a better way to reset the scroll to go to the very top of the page and show the large navigation bar title?

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            ScrollView {
                ScrollViewReader { value in
                    ForEach(0..<10) { i in
                        HStack {
                            Spacer()
                            NavigationLink(destination: Text("Destination"), label: { Text("\(i)") })
                                .padding(.bottom, 100)
                            Spacer()
                        }
                        .id(i)
                    }
                    .onAppear() {
                        value.scrollTo(0)
                    }
                }
            }
            .navigationBarTitle("Scroll Test")
        }
    }
}
sia
  • 256
  • 3
  • 14

1 Answers1

0

Currently the api does not allow for such functionality. Lets hope next week changes that.

Meanwhile you could implement this workaround: https://developer.apple.com/forums/thread/127737

It works by forcing the view to redraw by clearing out the data.

For your example to work you have to

  1. Create a @State variable like

@State var data = Array(0..<10)

  1. Replace your ForEach with

ForEach(data, id: \.self)

  1. Change your code within the onAppear

to

.onAppear {
    data = []
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
        data = Array(1..<10)
    }
Ali
  • 761
  • 1
  • 5
  • 24