[SwiftUI] ForEach

RudinP·2025년 7월 30일
0

Study

목록 보기
329/363

List와 다른점

  • 리스트는 테이블뷰 형태로 목록 표시
  • ForEach는 데이터를 나열만 하고 스타일 적용 X
  • ForEach 배치 방식은 임베드하고있는 뷰에 따라 달라짐.

    -> VStack

    -> HStack

언제 사용?

Sectioned List

  • 데이터를 섹션으로 구분할 때 사용

Delete/ Move

  • 편집 기능을 구현할 때 사용

Custom List UI

  • 목록 표시 UI 직접 구현 시 사용

1. 셀 뷰

struct ProductGridItem: View {
    let product: AppleProduct
    
    init(product: AppleProduct) {
        self.product = product
        
        print("init \(product.name)")
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            Text(product.category)
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Text(product.name)
                .font(.title2)
            
            Text(product.summary)
                .font(.caption)
                .multilineTextAlignment(.leading)
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding()                
                .background(.gray.opacity(0.1), in: RoundedRectangle(cornerRadius: 10))
            
            Spacer()
        }
    }
}

2. 그리드 뷰

struct Grid: View {
   var items = AppleProduct.sampleList
   
   var body: some View {
      VStack {
          ForEach(0 ..< 3) { row in
              HStack {
                  ForEach(0 ..< 2) { col in
                      ProductGridItem(product: items[row * 3 + col])
                  }
              }
          }
      }
      .padding()
   }
}

다만 iOS 14부터 그리드 추가로 이렇게 하지 않아도 된다.

profile
iOS 개발자가 되기 위한 스터디룸...

0개의 댓글