Tik-Tok like swiping scroll view in SwiftUI (iOS 17+)

Ivan Pryhara
1 min readJun 16, 2023

During WWDC engeniers from Apple introduced features that allows us to create Tik-Tok scrolling behavior only in a few lines of code

struct TikTokSwipingBehavior: View {
var body: some View {
ScrollView(.vertical) {
LazyVStack(spacing: 0) {
ForEach(0..<100) { i in
ZStack {
Rectangle()
.fill(Color.blue.opacity(0.6))
.containerRelativeFrame([.horizontal, .vertical])
Text("Video \(i+1)")
.font(.title)
.bold()
}
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.paging)
.ignoresSafeArea()
}
}

#Preview {
TikTokSwipingBehavior()
}

scrollTargetLayout and scrollTargetBehavior(_:)together allows to create a paging behavior on a scroll view.

scrolTargetLayout set all child views of a container to be a scroll target. Meanwhile scrollTargetBehavior sets actual attitude how scroll should work. So for paging like in our example, you would scroll item by item, i.e. paging(obviously). But there’s another option viewAligned. With this parameter your scroll view would work like with default implementation, though with a little difference — scroll always ends on the center of target view.

--

--