【Xcode/SwiftUI】水平方向のScrollViewを作る方法

実装

Model

import Foundation
import SwiftUI

struct Card: Identifiable, Equatable {
    let id = UUID()
    let color: Color

    static let allCards: [Card] = [
        Card(color: .red),
        Card(color: .blue),
        Card(color: .green),
        Card(color: .orange),
        Card(color: .purple)
    ]
}

CardView

import SwiftUI

struct CardView: View {
    let card: Card

    var body: some View {
        RoundedRectangle(cornerRadius: 10)
            .fill(card.color)
            .frame(width: 150, height: 150)
    }
}

HomeView (メインのView)

import SwiftUI

struct HomeView: View {
    @State private var selectedCard: Card?
    private let cards = Card.allCards

    var body: some View {
        VStack {
            Text("Horizontal Scroll View with Animation")
                .font(.custom(FontFamily.Caprasimo.regular, size: 16))
                .padding()

            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 20) {
                    ForEach(cards) { card in
                        CardView(card: card)
                            .scaleEffect(selectedCard == card ? 1.2 : 1.0)
                            .onTapGesture {
                                withAnimation {
                                    selectedCard = card
                                }
                            }
                    }
                }
                .padding(20)
            }
            .frame(height: 200)

            Spacer()
        }
    }
}