Creating Responsive UI Layouts with Stack Views and Spacers in SwiftUI

HStack, VStack, and ZStack are layout views in SwiftUI that allow you to position and arrange other views in specific ways. The HStack arranges views horizontally, placing them side by side. The VStack arranges views vertically, stacking them on top of one another. The ZStack arranges views in layers, allowing you to overlay one view on top of another. These views can be used individually or combined with other views and modifiers to create complex layouts and interfaces.

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 views 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