How to scroll to exact locations inside a scrollview
2024년 6월 21일About 2 min
How to scroll to exact locations inside a scrollview 관련
SwiftUI by Example
Back to Home
How to scroll to exact locations inside a scrollview | SwiftUI by Example
How to scroll to exact locations inside a scrollview
Updated for Xcode 16
Improved in iOS 18
SwiftUI’s scrollPosition()
modifier lets us make a ScrollView
move to a specific edge of the screen, jump to the top or bottom of its content, or scroll to an exact X/Y position, all in one.
This takes three steps, starting with a new property that stores the current scroll position:
@State private var position = ScrollPosition(edge: .top)
Next, you need to attach to the scrollview you're working with, like this:
.scrollPosition($position)
And finally, you can call various methods on that position
object to jump wherever you need:
// Go to the top or bottom edge
position.scrollTo(edge: .top)
position.scrollTo(edge: .bottom)
// Move to a particular view
position.scrollTo(id: "Avatar")
// Move to an exact X/Y coordinate
position.scrollTo(x: 0, y: 500)
Generally speaking I think you're likely to make ID-based scrolling your first choice, then edges, and finally exact coordinates last.
Here's a complete example, showing you how to move through items in a list in three different ways:
struct ContentView: View {
@State private var position = ScrollPosition(edge: .top)
var body: some View {
VStack {
ScrollView {
ForEach(0..<100) { i in
Text("Item \(i)")
.padding()
.id(i)
}
}
.scrollPosition($position)
HStack(spacing: 50) {
Button("Top") {
position.scrollTo(edge: .top)
}
Button("Bottom") {
position.scrollTo(edge: .bottom)
}
Button("Random") {
position.scrollTo(id: Int.random(in: 0..<100))
}
}
}
.font(.title)
}
}
Similar solutions…
How to indent the content or scroll indicators in a ScrollView | SwiftUI by Example
How to indent the content or scroll indicators in a ScrollView
How to flash the scroll bar indicators of a ScrollView or List | SwiftUI by Example
How to flash the scroll bar indicators of a ScrollView or List
How to hide the scroll indicators in ScrollView, List, and more | SwiftUI by Example
How to hide the scroll indicators in ScrollView, List, and more
How to make a scroll view move to a location using ScrollViewReader | SwiftUI by Example
How to make a scroll view move to a location using ScrollViewReader
How to make views scroll with a custom transition | SwiftUI by Example
How to make views scroll with a custom transition