Skip to content
DeveloperMemos

Applying Padding Only Vertically or Horizontally in SwiftUI

SwiftUI, Padding, User Interface1 min read

When building user interfaces in SwiftUI, padding is often used to add spacing around views, and make them more aesthetically pleasing. In this article, we will learn how to apply padding only vertically or horizontally in SwiftUI, and how it can improve the appearance of our user interface.

Applying Padding Only Vertically

In order to apply padding only vertically, we can use the .padding(.vertical, amount) modifier. The first parameter specifies that we want to apply padding vertically, and the second parameter specifies the amount of padding we want to apply.

1Text("Hello, World!")
2 .padding(.vertical, 20)

In the example above, we apply a padding of 20 points to the top and bottom of the text view. This will create some vertical space around the text, and improve the readability of the interface.

Applying Padding Only Horizontally

Similarly, we can apply padding only horizontally using the .padding(.horizontal, amount) modifier. The first parameter specifies that we want to apply padding horizontally, and the second parameter specifies the amount of padding we want to apply.

1Text("Hello, World!")
2 .padding(.horizontal, 20)

In the example above, we apply a padding of 20 points to the left and right of the text view. This will create some horizontal space around the text, and make it more visually appealing.

Applying Padding to a Specific Side

If we want to apply padding to only one side of a view, we can use the .padding(.leading, amount) or .padding(.trailing, amount) modifiers. The first parameter specifies which side we want to apply padding to, and the second parameter specifies the amount of padding we want to apply.

1Text("Hello, World!")
2 .padding(.leading, 20)

In the example above, we apply a padding of 20 points to the left of the text view. This will create some space to the left of the text, and make it more visually appealing.

Conclusion

In this article, we learned how to apply padding only vertically or horizontally in SwiftUI. We also learned how to apply padding to a specific side of a view. By using these techniques, we can improve the appearance of our user interface and create more visually appealing apps.