Programmatic scrolling in SwiftUI

SwiftUI ScrollView: Auto-scrolling / Manual scrolling to a particular position

Auto-scrolling or Manual scrolling to a particular position using ScrollViewReader in SwiftUI

Auto scrolling in SwiftUI

From iOS14, i.e. in SwiftUI 2, Apple provided an API "ScrollViewReader" which can be used to programmatically scroll to a position.

As per Apple documentation :

ScrollViewReader:
A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.

Case 1: Manual scroll to a position with the click of a button

struct ManualScroll: View {
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 0) {
ForEach(0..<100) { i in
Button("Scroll to row \(99 - i)") {
proxy.scrollTo(99-i)
}
Text("Row No : \(i)")
.frame(height: 32)
.id(i) //Set the Id
}
}
}
}
}
}

Case 2: Auto-scroll to the bottom as soon as the view appears

struct AutoScroll: View {
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 0) {
ForEach(0..<100) { i in
Text("Row No : \(i)")
.frame(height: 32)
.id(i) //Set the Id
}
}
}
.onAppear(perform: {
proxy.scrollTo(99)
})
}
}
}

Case 3: Auto-scroll to the bottom once the data is populated in the scroll view

There are times when our view is populated once we get the data from an API which might take some time. In that case, we will scroll to the bottom as soon as the data is received.

struct LoadNAuto: View {
@State var listCount : Int = 0
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 0) {
ForEach(0..<listCount, id: \.self) { i in
Text("Row No : \(i)")
.frame(height: 32)
.id(i) //Set the Id
}
}
}
.onChange(of: listCount, perform: { value in
proxy.scrollTo(99)
})
.onAppear(perform: {
listCount = 100
})
}
}
}
Sample project demonstrating auto-scroll

Download Project

You can find the complete source code of the project at

Keep Learning. Keep Sharing.

Consultant at GlobalLogic | iOS app developer | AWS Certified Solutions Architect - Associate