SwiftUI Stack Tutorial

Stacks in SwiftUI are equivalent with UIStackViews in UIKit. In this tutorial a vertical stack(VStack) and a horizontal stack(HStack) will be displayed. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIStackTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. The content view needs to return one view, so the following code won’t compile, since there are two text views.

struct ContentView: View {
    var body: some View {
        Text("Hello")
        Text("SwiftUI !!")
    }
}

Multiple views can be combined and embedded in stacks, which group views together. Command-click the text view to show the structured editing popover, and then choose Embed in VStack.

Also set the font of the Vstack to .largeTitle using the font modifier.

VStack() {
    Text("Hello")
    Text("SwiftUI !!")
}
.font(.largeTitle)

The preview shows the two text views vertically stacked.

The elements inside a stack can also be customized by adding spacing, which will enlarge the distance between the elements.

VStack(spacing: 50) {
    Text("Hello")
    Text("SwiftUI !!")
}
.font(.largeTitle)

By default, items in your stacks are aligned centrally. To align both text views horizontally to the leading edge, change the code to

VStack(alignment: .leading, spacing: 50) {
    Text("Hello")
    Text("SwiftUI !!")
}
.font(.largeTitle)
vstack-leading-alignment.png

Comment the VStack code block and add a horizontal stack to the content view.

struct ContentView : View {
    var body: some View {
        /*VStack(alignment: .leading, spacing: 50) {
            Text("Hello")
            Text("SwiftUI !!")
        }
        .font(.largeTitle)*/
            
        HStack(spacing: 20) {
            Text("Mac")
            Text("iPad")
            Text("iPhone")
            Text("Watch")
        }
        .font(.largeTitle)
    }
}

The text views inside the horizontal stack are positioned horizontally. The HStack is initialized with a spacing of 20.

The source code of the SwiftUIStackTutorial can be downloaded at the ioscreator repository on Github.