How do I build a horizontal, swipeable, paginated carousel in SwiftUI?

Asked on 2024-07-30

1 search

To build a horizontal, swipeable, paginated carousel in SwiftUI, you can use a combination of ScrollView and the paging behavior. Here's a basic example to get you started:

import SwiftUI

struct CarouselView: View {
    let items = Array(1...10).map { "Item \($0)" }
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 20) {
                ForEach(items, id: \.self) { item in
                    Text(item)
                        .frame(width: 200, height: 200)
                        .background(Color.blue)
                        .cornerRadius(10)
                        .shadow(radius: 5)
                }
            }
            .padding()
        }
        .pagingEnabled(true)
    }
}

struct ContentView: View {
    var body: some View {
        CarouselView()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example, ScrollView is used to create a horizontal scrollable view, and the pagingEnabled(true) modifier is applied to enable paging behavior, which makes the scroll view snap to the nearest item.

For more advanced customizations, such as creating unique scroll effects or transitions, you can refer to the session Create custom visual effects with SwiftUI. This session covers how to use the scrollTransition modifier to create custom scroll effects, such as rotating and offsetting items based on their position in the scroll view.

For example, to create a circular carousel effect, you can use the scrollTransition modifier:

ScrollView(.horizontal, showsIndicators: false) {
    HStack(spacing: 20) {
        ForEach(items, id: \.self) { item in
            Text(item)
                .frame(width: 200, height: 200)
                .background(Color.blue)
                .cornerRadius(10)
                .shadow(radius: 5)
                .scrollTransition { content, phase in
                    content
                        .rotationEffect(.degrees(phase.value * 360))
                        .offset(x: phase.value * 100)
                }
        }
    }
    .padding()
}
.pagingEnabled(true)

This code snippet demonstrates how to apply a rotation and offset effect to each item in the scroll view based on its position.

For more detailed information and examples, you can watch the session Create custom visual effects with SwiftUI.