SwiftUI series 5: Creating Smooth Scroll Transitions in SwiftUI
In this tutorial, we'll explore how to create smooth scroll transitions in SwiftUI using the scrollTransition modifier. We'll build a simple yet visually appealing scrollable view with animated cards. Let's dive into the code!
Setting Up the Project
First, create a new SwiftUI project in Xcode and replace the contents of your ContentView.swift file with the following code:
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView {
VStack {
ForEach(1..<20) { card in
RoundedRectangle(cornerRadius: 50)
.fill(.cyan.gradient)
.frame(height: 300)
.padding(5)
.scrollTransition(.animated.threshold(.visible(0.3))) { content, phase in
content
.scaleEffect(phase.isIdentity ? 1 : 0.1)
.opacity(phase.isIdentity ? 1 : 0)
}
}
}
}
}
}
Breaking Down the Code
Let's go through the main components of our ContentView:
-
ScrollView: We wrap our content in a
ScrollViewto make it scrollable. -
VStack: Inside the
ScrollView, we use aVStackto arrange our cards vertically. -
ForEach Loop: We create 19 cards (1 to 19) using a
ForEachloop. -
RoundedRectangle: Each card is represented by a
RoundedRectanglewith rounded corners. -
Styling: We apply a cyan gradient fill, set the height to 300, and add some padding to each card.
-
scrollTransition Modifier: This is where the magic happens! We use the
scrollTransitionmodifier to create smooth animations as the cards scroll into and out of view.