Skip to content

Instantly share code, notes, and snippets.

@appfrosch
Last active May 24, 2024 06:41
Show Gist options
  • Save appfrosch/60bf3b7f01219e7d94cf1ecf44d3b185 to your computer and use it in GitHub Desktop.
Save appfrosch/60bf3b7f01219e7d94cf1ecf44d3b185 to your computer and use it in GitHub Desktop.
When scrolling in a SwiftUI app, there might be two features a user would want to have: keep track of where the user is scrolling to and move the scroll position programmatically.
import SwiftUI
@main
struct so_ScrollViewWithPositionApp: App {
var body: some Scene {
WindowGroup {
ScrollContentView()
}
}
}
//see https://stackoverflow.com/questions/75617096/scrollviewreader-how-to-read-the-current-row
struct ScrollContentView: View {
//The position does *not* take the navigation bar into account!
@State private var currentScrollPosition: Int? = 278 - 2
var body: some View {
NavigationStack {
ScrollViewReader { proxy in
ScrollView {
//this does *not* seem to work in a `List` unfortunately …
LazyVStack {
ForEach(1..<300, id: \.self) { i in
Text("\(i)")
.id(i)
Divider()
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $currentScrollPosition)
.toolbar {
ToolbarItem(placement: .automatic) {
Button("Scroll to 50") {
withAnimation {
proxy.scrollTo(50, anchor: .top)
currentScrollPosition = 50
}
}
}
ToolbarItem(placement: .bottomBar) {
Text("Current anchor: \(String(describing: currentScrollPosition))")
}
}
}
}
}
}
#Preview {
ScrollContentView()
}
@appfrosch
Copy link
Author

Possible use cases for

  • keeping track of the user's scroll position: persist/cache that position
  • scroll to a position programmatically: scroll to that persisted/cached position when the user a revisiting that same screen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment