Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Adding Padding & Spacing in SwiftUI
Written by Team Kodeco

Padding and spacing are crucial tools in your SwiftUI toolkit, enabling you to create clear, visually distinct, and aesthetically pleasing interfaces. By mastering these modifiers, you can bring your app’s UI to the next level of polish.

Here’s an example of using padding and spacing modifiers within a VStack, HStack and individual views:

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      Text("Padding and Spacing").font(.largeTitle).padding(.bottom, 20)
      HStack(spacing: 15) {
        Image(systemName: "hare.fill")
          .font(.largeTitle)
          .foregroundColor(.green)
          .padding()
          .background(Color.orange.opacity(0.2))
          .clipShape(Circle())

        Image(systemName: "tortoise.fill")
          .font(.largeTitle)
          .foregroundColor(.green)
          .padding()
          .background(Color.orange.opacity(0.2))
          .clipShape(Circle())
      }

      Text("It's not about speed, it's about comfort!")
        .padding(.horizontal, 20)
        .padding(.vertical, 10)
        .background(Color.orange.opacity(0.2))
        .cornerRadius(10)
    }
    .padding()
  }
}

Your preview should look like this:

You can add padding and spacing throughout your layout.
You can add padding and spacing throughout your layout.

In this example:

  1. You’ve wrapped the entire layout in a VStack with a spacing of 20, which means there’s a 20-point gap between each child view.
  2. The title text “Padding and Spacing” has a bottom padding of 20 points, creating some room between it and the subsequent view.
  3. Within an HStack with 15 points of spacing, you have two images, a hare and a tortoise, each surrounded by a circular background. The padding modifier applied to each image creates space around the icon and the background.
  4. The quote at the bottom, “It’s not about speed, it’s about comfort!”, has its horizontal and vertical padding set separately, giving more control over the appearance. The background modifier with the cornerRadius modifier is used to give the text a background with rounded corners.
  5. Finally, the padding modifier applied to the parent VStack ensures there is space between the edge of the device’s screen and the stack’s contents.

By leveraging padding and spacing in SwiftUI, you can create a clean, spacious layout that enhances your app’s readability and aesthetics.

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.