DEV Community

Vaibhav Dwivedi
Vaibhav Dwivedi

Posted on

Scrollable Cards in iOS 18 - #30DaysOfSwift

Day 9: Smooth Scroll with Scrollable Cards! 🎴

For the ninth post of #30DaysOfSwift series, let's learn Scrollable Cards in SwiftUI.

Scrollable cards or stacks are perfect for showcasing content in a visually appealing, swipeable format.

Link to image example

Let’s build a horizontally scrolling stack of cards that showcases different content!

Steps to Create Scrollable Cards:

1. Set Up the Scrollable Card Layout:

  • We’ll use a ScrollView with a horizontal axis and a set of custom cards that users can swipe through.
import SwiftUI

struct ScrollableCardsView: View {
    let items = [
        CardItem(title: "SwiftUI Essentials", image: "swift"),
        CardItem(title: "Mastering Combine", image: "combine"),
        CardItem(title: "iOS Animations", image: "animation"),
        CardItem(title: "Networking with URLSession", image: "network")
    ]

    var body: some View {
        VStack(alignment: .leading) {
            Text("Trending Courses")
                .font(.largeTitle)
                .fontWeight(.bold)
                .padding(.leading)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 20) {
                    ForEach(items) { item in
                        CardView(item: item)
                            .frame(width: 300, height: 200)
                            .shadow(radius: 5)
                    }
                }
                .padding()
            }
        }
    }
}

struct CardView: View {
    let item: CardItem

    var body: some View {
        ZStack {
            Image(item.image)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: 300, height: 200)
                .clipped()

            VStack {
                Spacer()
                Text(item.title)
                    .font(.headline)
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(Color.black.opacity(0.7))
                    .foregroundColor(.white)
            }
        }
        .cornerRadius(15)
    }
}

struct CardItem: Identifiable {
    var id = UUID()
    var title: String
    var image: String
}

struct ContentView: View {
    var body: some View {
        ScrollableCardsView()
    }
}
Enter fullscreen mode Exit fullscreen mode

How does it look for you? Let me know too!

Happy Coding!

Top comments (0)