Sections 2: Building layouts with Stack views and Spacer

Overview Individually, HStack, VStack, and ZStack are simple views. HStack positions views in a horizontal line, VStack positions them in a vertical line, and ZStack overlays views on top of one another.

Learn how to use HStack, VStack, ZStack with spacing and alignment



VSTACK 

The VStack allows you to stack views vertically, from top to bottom. You can further customize the view by adding alignment or spacing to the VStack.

Code:

struct ContentView: View {
    var body: some View {
 
 
        //VSTACK
        VStack(alignment: .center, spacing: 16) {
 
            // Rectangle
            Rectangle()
                .frame(width: 50, height: 50)
 
            // Spacer
            Spacer()
 
            // Circle
            Circle()
                .frame(height: 50)
 
        }.frame(height : 100)
 
 
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


HSTACK 

The HStack is used to stack vfiews horizontally. Just like the VStack, you can set the alignment and space items.


Code:
import SwiftUI
 
struct ContentView: View {
    var body: some View {
 
 
        //HSTACK
        HStack(alignment: .center, spacing: 16) {
 
            // Spacer
            Spacer()
 
            // Rectangle
            Rectangle()
                .frame(width: 50, height: 50)
 
            // Spacer
            Spacer()
 
            // Circle
            Circle()
                .frame(height: 50)
 
        }.frame(height : 100)
 
 
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


ZSTACK 

ZStack is great for overlapping content. It stacks layers on top of each other, in a 3 dimentional plane. Since elements can float on top of each other, the alignment for ZStack will move all items at one.

Code:

import SwiftUI
 
struct ContentView: View {
    var body: some View {
 
 
        //ZStack
        ZStack(alignment: .center) {
 
 
            // Rectangle
            Rectangle()
                .frame(width: 80, height: 80)
 
 
           //Text
           Text("Hi")
                .foregroundColor(.white)
 
 
        }
        .frame(width: 100)
 
 
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


SPACER 

By default, stacks in SwiftUI will take the minimum space and align to the center. The Spacer is essential for pushing the content to use the maximum space. It can be useful for aligning elements as well.

Comments


Copyright © 2022 | boltuix.com | Privacy Policy.