Structure¶
ScrollViewProxy¶
A proxy value allowing the scrollable views within a view hierarchy to be scrolled programmatically.¶
Declaration¶
struct ScrollViewProxy
Overview¶
Scrolling to an item¶
To programmatically scroll to a particular item in your ScrollView, use scrollTo(_:anchor:). ScrollViewProxy is a type that allows you to control a ScrollView, and can be obtained using a ScrollViewReader.
For example:
struct ExampleView: View {
var body: some View {
ScrollView {
ScrollViewReader { (proxy: ScrollViewProxy) in
Button("Jump to #32") {
proxy.scrollTo(32)
}
ForEach(1..<101) { number in
Text("Item #\(number)")
.id(number)
}
}
}
}
}

In this example, clicking the button reading "Jump to #32", will cause the ScrollView to scroll to the item with the ID of the value 32. To assign an ID to a view, use id(_:) as is done inside the ForEach, for each element.
The call of proxy.scrollTo(32) causes the ScrollView to scroll to the text reading "Item #32", with that text centered vertically in the ScrollView's bounds. To change the anchor of the finalled scrolled-to destination, specify an anchor via scrollTo(_:anchor:). For example:
struct ExampleView: View {
var body: some View {
ScrollView {
ScrollViewReader { (proxy: ScrollViewProxy) in
Button("Jump to #32") {
proxy.scrollTo(32, anchor: .top)
}
ForEach(1..<101) { number in
Text("Item #\(number)")
.id(number)
}
}
}
}
}

In this example, the ScrollView still scrolls to "Item #32", but this Text is seen at the top of the ScrollView, rather than it's vertical center. The anchor parameter uses a type, UnitPoint, to determine the relative alignment (relative to the scroll view's bounds) of the scrolled-to item.
Add a transition to your scrollTo(_:anchor:) with withAnimation(_:_:). For example:
struct ExampleView: View {
var body: some View {
ScrollView {
ScrollViewReader { (proxy: ScrollViewProxy) in
Button("Jump to #32") {
withAnimation(.easeInOut(duration: 60)) {
proxy.scrollTo(32, anchor: .top)
}
}
ForEach(1..<101) { number in
Text("Item #\(number)")
.id(number)
}
}
}
}
}

Availability¶
iOS 14.0+
macOS 11.0+
tvOS 14.0+
watchOS 7.0+
Topics¶
Instance Method¶
scrollTo(_:anchor:) Scroll to a section given a specific identifier.