Using stacks in SwiftUI allows you to arrange multiple views into a single coherent view with certain properties. HStack allows to arrange its child views in a horizontal line. VStack allows to arrange its child views in a vertical line, and ZStack allows to overlap its child views on top of each other. Stacks can further be customized with alignment and spacing in order to modify their appearance.
Example usage of HStack to place two views – an image and a text label next to each other:
HStack {
Image(systemName: "bookmark")
Text("Simple Swift Guide")
}
Another example of HStack with larger spacing between its child views:
HStack(spacing: 30) {
Image(systemName: "bookmark")
Text("Simple Swift Guide")
}
Example usage of VStack to place two views – an HStack and a text label above each other:
VStack {
HStack {
Image(systemName: "bookmark")
Text("Simple Swift Guide")
}
Text("A blog about iOS development")
}
Another example of VStack making sure to align its child views to the left:
VStack(alignment: .leading) {
HStack {
Image(systemName: "bookmark")
Text("Simple Swift Guide")
}
Text("A blog about iOS development")
}
Example usage of ZStack to overlap a text label on top of an image:
ZStack {
Image(systemName: "bubble.left").resizable().frame(width: 200.0, height: 200.0)
Text("Simple Swift Guide")
}
Related tutorials:
- SwiftUI Text View complete tutorial
- SwiftUI TextField complete tutorial
- How to create a Button in SwiftUI
Questions, comments or suggestions? Follow us on Twitter @theswiftguide