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.