This implementation creates a smooth, swipeable carousel with page indicators. Here are the key components:
- The
TabView
is set to usePageTabViewStyle()
, which enables the carousel-like swiping behavior. - Page indicators are shown using
indexViewStyle(PageIndexViewStyle())
- Each slide is tagged with an index to track the current position.
- The
@State
variablecurrentTab
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:
- Modify the
CarouselCard
view to display your content - Adjust the padding and spacing.
- Change the animation timing.
- Add auto-scrolling functionality.
- Customize the page indicator appearance.
Thanks for reading!
This is great.