Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Understanding HStack & Spacer in SwiftUI
Written by Team Kodeco

When building a user interface with SwiftUI, you’ll often need to position elements horizontally. One of the most useful tools for this is the HStack view, which arranges its children from left to right. Sometimes, you may need to control the spacing between elements, which can be accomplished with Spacers.

To use HStack, simply add your views as children, like this:

struct ContentView: View {
  var body: some View {
    HStack {
      Image(systemName: "ant.circle.fill")
        .resizable()
        .scaledToFit()
        .frame(width: 50)
      Text("Cute Ant")
        .font(.title)
        .padding(.leading, 10)
      Spacer()
      Image(systemName: "ladybug")
        .resizable()
        .scaledToFit()
        .frame(width: 50)
      Text("Cheerful Ladybug")
        .font(.title)
        .padding(.leading, 10)
    }
    .padding()
  }
}

Your preview should look like this:

Use HStack to lay out content horizontally.
Use HStack to lay out content horizontally.

This example uses HStack to place two sets of Image and Text views side by side, representing a cute ant and a cheerful ladybug. Each set includes an image of an ant or ladybug and a corresponding Text view that labels the image.

The Image view uses SF Symbols as image sources, which are resizable and scaled to fit within a specified frame size of 50 points in width.

The Text views use a .font(.title) modifier to increase the font size and .padding(.leading, 10) to add a 10-point padding on the left side, which creates a space between the text and its preceding image.

A Spacer is placed between the two sets of Image and Text views. It occupies the maximum available space and pushes the views on either side as far apart as possible, effectively centering the text of the cheerful ladybug within the remaining space.

By leveraging HStack and Spacer, you can achieve precise control over the horizontal layout and spacing of your views in SwiftUI. This gives you the flexibility to design complex and aesthetically pleasing user interfaces with ease.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.