History
Loading...
Loading...
September 6, 2025
ScrollViewReader with .scrollTo() to programmatically scroll to specific views by their ID. Perfect for implementing 'scroll to top' buttons or navigating to specific content sections without complex gesture handling.This pattern uses a separate state variable to trigger scroll actions and wraps the scrollTo call in withAnimation for smooth transitions. The state is reset after scrolling to prevent unintended repeated scrolling.
struct ContentView: View {
@State private var scrollTarget: Int?
var body: some View {
VStack {
Button("Scroll to Item 50") {
withAnimation(.easeInOut(duration: 0.8)) {
scrollTarget = 50
}
}
ScrollViewReader { proxy in
ScrollView {
LazyVStack {
ForEach(1...100, id: \.self) { index in
Text("Item \(index)")
.frame(height: 60)
.id(index)
}
}
}
.onChange(of: scrollTarget) { target in
if let target = target {
proxy.scrollTo(target, anchor: .center)
scrollTarget = nil
}
}
}
}
}
}Separating scroll triggers from the ScrollViewReader logic creates cleaner, more predictable code. The animation wrapper ensures smooth user experience, while resetting the trigger state prevents bugs when the same target is selected multiple times.