iOS/SwiftUI

[SwiftUI] Stack

HarryJeonn 2022. 4. 24. 15:46

Stack을 어떤식으로 사용하는지 알아보자

SwiftUI에 Stack은 VStack, HStack, ZStack 3가지 종류가 있다.

VStack

struct VstackView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            Text("글자")
                .font(.system(size: 30))
                .fontWeight(.bold)
            
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.red)
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.yellow)
            
            // Space 크기 조절 가능
            Spacer()
                .frame(height: 50)
            
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.blue)
        }
        .frame(width: 300)
        .background(Color.green)
    }
}

HStack

struct HstackView: View {
    var body: some View {
        HStack(alignment: .center) {
//            Divider()
            
//            Rectangle()
//                .frame(width: 100, height: 100)
//                .foregroundColor(.red)
            
            Image(systemName: "flame.fill")
                .foregroundColor(.white)
                .background(Color.red)
                .font(.system(size: 70))
            
            Spacer()
                .frame(width: 20)
            
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.yellow)
            
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.blue)
        }
        .padding()
        .background(Color.green)
    }
}

ZStack

struct ZstackView: View {
    var body: some View {
        ZStack {
            // 위에서 아래로 내려오면서 쌓여감
//            Rectangle()
//                .frame(width: 150, height: 150)
//                .foregroundColor(.red)
//
//            Rectangle()
//                .frame(width: 100, height: 100)
//                .foregroundColor(.yellow)
//
//            Rectangle()
//                .frame(width: 50, height: 50)
//                .foregroundColor(.blue)
            
            
            // zIndex로 순서를 변경할 수 있음
            Rectangle()
                .frame(width: 50, height: 50)
                .foregroundColor(.red)
                .zIndex(2)
            
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.yellow)
                .zIndex(1)
            
            Rectangle()
                .frame(width: 150, height: 150)
                .foregroundColor(.blue)
                .zIndex(0)
        }
        .background(Color.green)
    }
}

zIndex로 View의 우선순위를 정할 수 있다.