Articles, podcasts and news about Swift development, by John Sundell.

Stacking views in SwiftUI

Published on 06 Jun 2019
Discover page available: SwiftUI

SwiftUI ships with 3 main stack types — that enable you to easily align content on either the X, Y, or Z axis. And, since all SwiftUI views are composable, they can also be nested in order to build really complex UIs:

The above will result in a view which content looks like this:

struct MyView: View {
    var body: some View {
        // A ZStack stacks its child views on top of each other
        // in terms of depth, from back to front.
        ZStack {
            Color.gray
            // A VStack stacks its child views vertically, from
            // top to bottom.
            VStack {
                // The ForEach construct enables you to create
                // multiple views in one go, for example by
                // mapping a collection of elements to views.
                ForEach(0..<5) { _ in
                    // A HStack aligns its child views horizontally,
                    // from the leading to the trailing edge.
                    HStack {
                        Text("Leading")
                        Text("Trailing")
                    }
                }
            }
        }
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.