Skip to content
DeveloperMemos

Adding Empty Space with SwiftUI

SwiftUI, Layout, User Interface1 min read

When it comes to crafting compelling and visually appealing user interfaces, the ability to control the spacing between elements is crucial. In SwiftUI, achieving this can be done in various ways. In this article, we'll explore how to add empty space within SwiftUI views to optimize layout and design.

Using Spacer

One of the simplest yet powerful ways to add empty space in a SwiftUI layout is by using the Spacer view. This view expands to fill the available space along its axis, pushing other views toward the edges.

Let's consider an example where we want to create some vertical space between two text views:

1VStack {
2 Text("Hello,")
3 Spacer()
4 Text("SwiftUI!")
5}

In this case, the Spacer view will push the second text view to the bottom of the screen, effectively creating empty space between the two text elements.

Adding Padding

Another method to create space around elements is by adding padding directly to the views. The padding modifier allows us to specify the amount of padding around a view, either uniformly or in specific directions.

For instance, to add padding around a text view, we can use the following code:

1Text("Explore SwiftUI")
2 .padding(20)

This adds 20 points of padding around the text on all sides.

Utilizing Empty Views

Sometimes, achieving the desired layout may require the use of empty views. These views serve as placeholders to occupy space in the layout without necessarily displaying any content. We can leverage this approach to create precise spacing between elements.

Consider the following example, where we want to add some horizontal space between two image views:

1HStack {
2 Image(systemName: "star")
3 EmptyView()
4 .frame(width: 50)
5 Image(systemName: "star.fill")
6}

By inserting an EmptyView with a specified width between the two images, we're able to achieve the desired spacing.