Create carousal view in swiftUI using tabview and tab?

By | February 11, 2025

This implementation creates a smooth, swipeable carousel with page indicators. Here are the key components:

  1. The TabView is set to use PageTabViewStyle(), which enables the carousel-like swiping behavior.
  2. Page indicators are shown using indexViewStyle(PageIndexViewStyle())
  3. Each slide is tagged with an index to track the current position.
  4. The @State variable currentTab keeps track of the selected slide.

The complete code is as given below. Inline comments are given for better understanding of above points.

import SwiftUI

struct CarouselView: View {
    @State private var currentTab = 0
    
    // Sample data - replace with your own model
    private let items = [
        "First Slide",
        "Second Slide",
        "Third Slide",
        "Fourth Slide"
    ]
    
    var body: some View {
        TabView(selection: $currentTab) {
            ForEach(0..<items.count, id: \.self) { index in
                CarouselCard(text: items[index])
                    .tag(index)
            }
        }
        .tabViewStyle(PageTabViewStyle()) // This enables the carousel effect
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
    }
}

// Card view for each carousel item
struct CarouselCard: View {
    let text: String
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 15)
                .fill(Color.blue.opacity(0.2))
                .shadow(radius: 5)
            
            Text(text)
                .font(.title)
                .foreground(Color.primary)
        }
        .padding(.horizontal, 20)
    }
}

// Preview provider
struct CarouselView_Previews: PreviewProvider {
    static var previews: some View {
        CarouselView()
    }
}

To customize this carousel, you can:

  1. Modify the CarouselCard view to display your content
  2. Adjust the padding and spacing.
  3. Change the animation timing.
  4. Add auto-scrolling functionality.
  5. Customize the page indicator appearance.

Thanks for reading!

One thought on “Create carousal view in swiftUI using tabview and tab?

Leave a Reply

Your email address will not be published. Required fields are marked *