Member-only story
Snap to Item Scrolling in SwiftUI
Implement Snap to Item scrolling in SwiftUI using this custom ViewModifier technique. This quick tip shows how it can be implemented for horizontal stacks.

One of the biggest things I’m missing with SwiftUI is the ability to snap to views as I scroll in a ScrollView
. Below is a technique I use to implement snapping on my HStack
with a custom ViewModifier
.
Before getting started, please consider subscribing using this link, and if you aren’t reading this on TrailingClosure.com, please come check us out sometime!
Overview
Instead of using a ScrollView
, this technique uses an HStack
with a dynamically changing x-offset to simulate scrolling. To change the offset I use a DragGesture
to calculate the scroll distance. You'll see below inside the DragGesture
onChanged()
closure that I update the dragOffset
. This makes the HStack
appear to scroll as the user drags across the screen. Finally, when the DragGesture
function onEnded()
is called, I…