Skip to content
DeveloperMemos

Using Spacer in SwiftUI

SwiftUI, Spacer1 min read

The Spacer view is an essential component when it comes to managing the layout and spacing of elements in SwiftUI. It provides a flexible way to distribute available space within a container view by expanding or shrinking as needed. In this article, we'll discuss different scenarios where Spacer can be used effectively.

Creating Space Between Views

One common use case for Spacer is to add space between views. By placing a Spacer between two views, it pushes them apart, creating empty space based on the available screen area. Here's an example:

1VStack {
2 Text("Hello")
3 Spacer()
4 Text("World")
5}

In this code snippet, the Spacer expands to fill the available space between the "Hello" and "World" Text views, pushing them towards the top and bottom respectively. This results in vertical spacing between the two views.

Equal Spacing Between Multiple Views

Spacer becomes particularly handy when you want to distribute multiple views evenly along an axis. By using multiple Spacer views together with the HStack or VStack, you can achieve equal spacing between the views. Let's consider an example:

1HStack {
2 Button("Button 1") { }
3 Spacer()
4 Button("Button 2") { }
5 Spacer()
6 Button("Button 3") { }
7}

In this case, the Spacer views distribute the available horizontal space equally between the three buttons in the HStack, resulting in consistent spacing between them. You can apply the same concept with vertical spacing using VStack.

Expanding and Shrinking Views

Another powerful aspect of Spacer is its ability to expand or shrink to fill available space. This behavior can be useful when you want to prioritize the size of specific views while allowing others to adjust dynamically. Consider the following example:

1VStack {
2 Text("Title")
3 Spacer()
4 Image("picture")
5 .resizable()
6 .aspectRatio(contentMode: .fit)
7 Spacer()
8 Text("Description")
9}

In this code snippet, the Spacer views allow the Image to take up as much vertical space as needed, while the "Title" and "Description" Text views occupy only the necessary space. The Image will expand or shrink based on the available space, maintaining its aspect ratio.

Spacer is a versatile component in SwiftUI that empowers you with fine-grained control over the spacing and layout of your views. By utilizing Spacer effectively, you can create visually appealing and responsive interfaces.