Learn how to arrange views using VStack, HStack, and ZStack to create complex layouts.
A VStack
arranges its children vertically.
VStack(alignment: .leading, spacing: 10) {
Text("Hello, World!")
Text("Welcome to SwiftUI")
}
Explanation:
alignment: .leading
: Aligns the child views to the leading edge (left side).spacing: 10
: Sets the space between child views to 10 points.Text("Hello, World!")
: Displays a text view with the string "Hello, World!".Text("Welcome to SwiftUI")
: Displays another text view with the string "Welcome to SwiftUI".A HStack
arranges its children horizontally.
HStack(spacing: 20) {
Text("SwiftUI")
Image(systemName: "star.fill")
}
Explanation:
spacing: 20
: Sets the space between child views to 20 points.Text("SwiftUI")
: Displays a text view with the string "SwiftUI".Image(systemName: "star.fill")
: Displays a system image with the name "star.fill".A ZStack
overlays its children, placing them on top of each other.
ZStack {
Image("background")
Text("Overlay Text")
.font(.largeTitle)
.foregroundColor(.white)
}
Explanation:
Image("background")
: Displays an image with the name "background".Text("Overlay Text")
: Displays a text view with the string "Overlay Text"..font(.largeTitle)
: Sets the font style to large title, making the text larger..foregroundColor(.white)
: Sets the text color to white.Combining different stacks to create complex layouts:
VStack {
HStack {
Text("Leading")
Spacer()
Text("Trailing")
}
.padding()
ZStack {
Circle()
.fill(Color.blue)
.frame(width: 100, height: 100)
Text("Centered")
.foregroundColor(.white)
}
}
Explanation:
HStack
: A horizontal stack that arranges its children horizontally.Text("Leading")
: Displays a text view with the string "Leading".Spacer()
: Adds flexible space to push the views to the edges.Text("Trailing")
: Displays a text view with the string "Trailing"..padding()
: Adds padding around the horizontal stack.ZStack
: An overlay stack that places its children on top of each other.Circle().fill(Color.blue)
: Draws a blue circle..frame(width: 100, height: 100)
: Sets the size of the circle to 100x100 points.Text("Centered")
: Displays a text view with the string "Centered"..foregroundColor(.white)
: Sets the text color to white.