새소식

iOS/SwiftUI

[SwiftUI] 공식문서 파헤치기 (2) [Stack]

  • -

HStack : 수평방향(Horizontal)으로 Stack을 쌓는 View 

 

HStack | Apple Developer Documentation

A view that arranges its subviews in a horizontal line.

developer.apple.com

var body: some View {
    HStack(
        alignment: .top,
        spacing: 10
    ) {
        ForEach(
            1...5,
            id: \.self
        ) {
            Text("Item \($0)")
        }
    }
}

 

 

Result 

 

 

Code에서 ForEach문이 등장한다.

 

 


ForEach : 식별된 데이터의 기본 컬렉션에서 요구에 따라 View를 계산하는 Structure

 

ForEach | Apple Developer Documentation

A structure that computes views on demand from an underlying collection of identified data.

developer.apple.com

 

Q. SwiftUI에서는 for문이 아니라 ForEach을 사용하는 걸까?

A. ForEach는 Structure(구조체)이다. return type이 Content이기 때문에 일반적으로 사용하는 ForEach문이 아니다.

 

 


LazyHStack : 필요할 때만 항목을 생성하는 HStack

 

LazyHStack | Apple Developer Documentation

A view that arranges its children in a line that grows horizontally, creating items only as needed.

developer.apple.com

 

HStack에서 Lazy가 붙었다.

 

Lazy : 화면에 렌더링 할 때까지 요소들을 생성하지 않는다.

 

아래는 ScrollView에 LazyHStack을 포함한 예시이다. 

ScrollView(.horizontal) {
    LazyHStack(alignment: .top, spacing: 10) {
        ForEach(1...100, id: \.self) {
            Text("Column \($0)")
        }
    }
}

 

 


VStack : 수직방향(Vertical)으로 Stack을 쌓는 View

 

VStack | Apple Developer Documentation

A view that arranges its subviews in a vertical line.

developer.apple.com

var body: some View {
    VStack(
        alignment: .leading,
        spacing: 10
    ) {
        ForEach(
            1...10,
            id: \.self
        ) {
            Text("Item \($0)")
        }
    }
}

 

Result

 

 


LazyVStack : LazyHStack과 동일한 개념이지만 VStack

 

LazyVStack | Apple Developer Documentation

A view that arranges its children in a line that grows vertically, creating items only as needed.

developer.apple.com

 

아래는 LazyHStack에서 LazyVStack으로 변경된 ScrollView 예시이다.

ScrollView {
    LazyVStack(alignment: .leading) {
        ForEach(1...100, id: \.self) {
            Text("Row \($0)")
        }
    }
}

 

 


ZStack : V/HStack과 달리 3차원의 View(Overlay: 덮어쓰다)

 

ZStack은 각각의 연속적인 하위 View에 이전 View보다 더 높은 Z 축을 할당합니다.

 

아래 코드는 ZStack에 100x100 사각형을 겹치지 않도록 10px씩 OffSet한 코드입니다

let colors: [Color] =
    [.red, .orange, .yellow, .green, .blue, .purple]


var body: some View {
    ZStack {
        ForEach(0..<colors.count) {
            Rectangle()
                .fill(colors[$0])
                .frame(width: 100, height: 100)
                .offset(x: CGFloat($0) * 10.0,
                        y: CGFloat($0) * 10.0)
        }
    }
}

 

Result

 

 

 

 

728x90

'iOS > SwiftUI' 카테고리의 다른 글

[SwiftUI] Button  (0) 2024.04.21
[SwiftUI] 공식문서 파헤치기 (3) [Spacer / Divider]  (0) 2023.08.12
[SwiftUI] 공식문서 파헤치기 (1) [SwiftUI]  (0) 2023.08.05
[SwiftUI] Stack  (0) 2023.01.30
[SwiftUI] Image  (0) 2023.01.14
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.