SwiftUI Spacer

Jerry PM
3 min read6 days ago

Some tips and tricks for using spacer()

Design by Author

In SwiftUI, there is a component called Spacer, which is used to create spacing between other components.

Below, in addition to the common usage, there are some tips and tricks for using Spacer more effectively.

✧ Basic Usage

This is a common usage by placing a spacer between components such as “Text”.

// Spacer between comp
HStack {
Text("Left")
Spacer()
Text("Right")
}

// Center content with equal spacers
// This is actually often used to position components in the center.
VStack {
Spacer()
Text("Vertically Centered")
Spacer()
}

You probably already know how to use it. Next, here are some tips that might be rarely used.

✧ Customizing Spacers

  • Minimum length spacer ➔ This spacer ensures a guaranteed minimum size while remaining flexible
  • Fixed width spacer ➔ Useful when you want a non-flexible spacer to act as a fixed gap between components.
  • Frame with flexible ➔ Ensuring flexibility while maintaining a guaranteed minimum size.
// Minimum length spacer
Spacer(minLength: 50)

// Fixed width spacer using frame
Spacer()
.frame(width: 20)

// Frame with flexible width but minimum…

--

--

No responses yet