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:
In this example:
- 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. - The title text “Padding and Spacing” has a bottom
padding
of 20 points, creating some room between it and the subsequent view. - Within an
HStack
with 15 points of spacing, you have two images, a hare and a tortoise, each surrounded by a circular background. Thepadding
modifier applied to each image creates space around the icon and the background. - 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. Thebackground
modifier with thecornerRadius
modifier is used to give the text a background with rounded corners. - Finally, the
padding
modifier applied to the parentVStack
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.