how to create paged content in scrollview in swiftui in swift

To create paged content in a ScrollView in SwiftUI, we can make use of the ScrollViewReader and GeometryReader views.

Here's an example code that demonstrates how to use this approach:

main.swift
struct PagedScrollView<Content: View>: View {
    let pageCount: Int
    let content: (Int) -> Content
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            ScrollViewReader { scrollView in
                LazyHStack(spacing: 0) {
                    ForEach(0..<pageCount) { index in
                        GeometryReader { proxy in
                            content(index)
                                .frame(width: proxy.size.width, height: proxy.size.height)
                                .id(index)
                        }
                        .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                    }
                }
                .onChange(of: currentPage, perform: { value in
                    withAnimation {
                        scrollView.scrollTo(value, anchor: .leading)
                    }
                })
            }
        }
    }
    
    private var currentPage: Int {
        Int(floor((scrollViewOffset + UIScreen.main.bounds.width / 2) / UIScreen.main.bounds.width))
    }
    
    private func offset(for index: Int) -> CGFloat {
        CGFloat(index) * UIScreen.main.bounds.width
    }
    
    @State private var scrollViewOffset: CGFloat = 0
}

1291 chars
38 lines

In this code, we define a PagedScrollView view that accepts a pageCount and a closure that returns a View for a given page index. The view uses a ScrollViewReader to monitor the scroll offset, and a LazyHStack to lay out the pages horizontally.

Each page view is wrapped in a GeometryReader, which provides the view's size so that we can size each page appropriately. We give each page a unique ID using the id(_:) modifier, which allows the ScrollViewReader to scroll to a specific page.

Finally, we define a computed property called currentPage that determines the current page index based on the scroll offset. We use this property in the .onChange(of:perform:) modifier to animate the scroll view to the current page whenever it changes.

With this PagedScrollView, you can easily create paged content in a scroll view in SwiftUI.

related categories

gistlibby LogSnag