Last active
May 24, 2024 06:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Possible use cases for