How do I paginate a scroll view in SwiftUI
Asked on 2024-08-04
1 search
To paginate a scroll view in SwiftUI, you can use the paging
behavior provided by the ScrollView
. This allows you to create a pagination effect where the content snaps to discrete pages as you scroll.
Here's a basic example of how to implement pagination in a horizontal ScrollView
:
import SwiftUI
struct PaginatedScrollView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
ForEach(0..<10) { index in
Text("Page \(index)")
.frame(width: UIScreen.main.bounds.width, height: 200)
.background(Color.blue)
.foregroundColor(.white)
.font(.largeTitle)
}
}
}
.pagingEnabled(true)
}
}
struct PaginatedScrollView_Previews: PreviewProvider {
static var previews: some View {
PaginatedScrollView()
}
}
In this example, the ScrollView
is set to scroll horizontally, and the HStack
contains multiple pages. The pagingEnabled(true)
modifier ensures that the scroll view snaps to each page as you scroll.
For more advanced scroll effects and custom pagination, you can refer to the session Create custom visual effects with SwiftUI which covers various scroll effects and transitions in SwiftUI.

Create custom visual effects with SwiftUI
Discover how to create stunning visual effects in SwiftUI. Learn to build unique scroll effects, rich color treatments, and custom transitions. We’ll also explore advanced graphic effects using Metal shaders and custom text rendering.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.

Demystify SwiftUI containers
Learn about the capabilities of SwiftUI container views and build a mental model for how subviews are managed by their containers. Leverage new APIs to build your own custom containers, create modifiers to customize container content, and give your containers that extra polish that helps your apps stand out.