konohazukux / swiftSample

0 stars 0 forks source link

VStackの中をfor文にしたい #14

Closed konohazukux closed 4 months ago

konohazukux commented 4 months ago

VStack の中で ForEach を使用してループを回すことで、動的に ProductItemsView を生成できます。以下のようにコードを修正してください:

//
//  ContentView.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import SwiftUI

struct ContentView: View {
  @StateObject private var viewModel = ProductItemViewModel()

  var body: some View {
    NavigationView {
      ScrollView(.vertical, showsIndicators: false) {
        VStack {
          ForEach($viewModel.productItems) { $productItem in
            ProductItemsView(productItem: $productItem)
          }
        }
      }
      .listStyle(PlainListStyle()) // Remove default styling
      .navigationTitle("To-Do List")
    }
  }
}

#Preview {
  ContentView()
}

struct ProductItemsView: View {
  @Binding var productItem: ProductItem

  var body: some View {
    VStack(alignment: .leading) {  // alignment を .leading に変更
      HStack {
        Text(productItem.title)
        Spacer()
        Image(systemName: productItem.isCompleted ? "checkmark.circle.fill" : "circle")
          .foregroundColor(productItem.isCompleted ? .green : .gray)
          .onTapGesture { }
      }
      ScrollView(.horizontal, showsIndicators: false) {
        HStack(alignment: .top) {  // alignment を .top に変更
          ForEach(0..<5) { index in
            RoundedRectangle(cornerRadius: 10)
              .fill(Color.blue)
              .frame(width: 100, height: 100)
              .overlay(
                Text("Item \(index)")
                  .foregroundColor(.white)
              )
              .padding(5)
          }
        }
      }
    }
    .padding(.horizontal, 10)
  }
}

//
//  ToDoItem.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import Foundation

struct ProductItem: Identifiable {
  let id = UUID()
  let title: String
  var isCompleted: Bool

  mutating func toggleCompletion() {
    isCompleted.toggle()
  }
}

//
//  ToDoViewModel.swift
//  MyListApp
//
//  Created by TAKESHI SHIMADA on 2024/07/02.
//

import Foundation

class ProductItemViewModel: ObservableObject {
  @Published var productItems = [
    ProductItem(title: "Buy groceries", isCompleted: false),
    ProductItem(title: "Walk the dog", isCompleted: true),
    ProductItem(title: "Read a book", isCompleted: false)
  ]

  func toggleCompletion(of item: ProductItem) {
    if let index = productItems.firstIndex(where: { $0.id == item.id }) {
      productItems[index].toggleCompletion()
    }
  }
}

この修正により、viewModel.productItems 内のすべてのアイテムについて ProductItemsView を動的に生成し、VStack の中に表示します。これで、アイテム数に応じてリストが自動的に更新されます。

konohazukux commented 4 months ago

bc03b3e79fc3ef6ec646b367fbbfca1bad492f93