Auto scroll to a specific position in SwiftUI
In the last post, we learned how to Scroll to a specific position with a button click. But what if we don’t want to do it manually like we want to do it without any user interaction? how do we achieve this behavior?, scrolling to any specific position in SwiftUI automatically. So that we will see in this post.
Automatically scrolling to a specific position
It is very easy to scroll to a specific position in SwiftUI. We just have to use the .onAppear
modifier inside the ScrollViewReader.
struct ContentView: View { var body: some View { ScrollView{ ScrollViewReader{ proxy in ForEach(0..<20){ index in Text("hello world") .font(.title2) .foregroundColor(.purple) .frame(maxWidth: .infinity) .frame(height: 50) .background(Color.white) .cornerRadius(8) .shadow(color: .gray, radius: 6) .padding(5) .id(index) } .onAppear{ withAnimation(.spring()){ // scroll to bottom proxy.scrollTo(19,anchor: .center) } } Button(action: { //scroll to top withAnimation(.spring()){ proxy.scrollTo(0,anchor: .top) } } , label: { Text("Move to Top").font(.headline) }) .frame(maxWidth: .infinity) .frame(height: 60) .background(Color.black) .cornerRadius(8) .foregroundColor(Color.white) .shadow(radius: 20) .padding(5) } } } }
- .onAppear: It is the modifier that performs an action as soon as the view appears on the screen.
So when the app runs and the view appears on the screen the .
onAppear
modifier calls the proxy’s scrollTo
function. In the function, we have given the id of our bottom view which is 19. So the scrollTo
function will automatically scroll us to the bottom of the view just when the view appears without any user interaction.
Wait for few seconds to see the output below.
Leave a Reply