make a scrollview snap to page

Generated on 8/2/2024

1 search

To make a ScrollView snap to a page in SwiftUI, you can use the paging behavior provided by SwiftUI. This can be achieved by setting the paging modifier on your ScrollView. Here's an example of how you can do this:

import SwiftUI

struct PagingScrollView: 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: UIScreen.main.bounds.height)
                        .background(index % 2 == 0 ? Color.blue : Color.green)
                }
            }
        }
        .paging()
    }
}

struct PagingScrollView_Previews: PreviewProvider {
    static var previews: some View {
        PagingScrollView()
    }
}

In this example, the ScrollView is set to scroll horizontally, and the paging modifier is applied to make it snap to each page as you scroll.

For more advanced scroll effects, you can refer to the session Create custom visual effects with SwiftUI which covers various scroll effects and transitions you can apply to your ScrollView.