0
0
iOS Swiftmobile~5 mins

Spacer and padding in iOS Swift

Choose your learning style9 modes available
Introduction

Spacer and padding help you control space and distance between things on the screen. They make your app look neat and easy to use.

To push buttons or text apart evenly in a row or column.
To add space around a text label so it doesn't touch the edges.
To center a view by adding space on both sides.
To separate sections in a list with some breathing room.
To avoid UI elements sticking too close to the screen edges.
Syntax
iOS Swift
Spacer()
.padding(EdgeInsets(top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat))

Spacer() creates flexible empty space that grows to fill available room.

padding() adds fixed space around a view. You can specify edges and size.

Examples
This puts "Left" text on the left and "Right" text on the right with space in between.
iOS Swift
HStack {
  Text("Left")
  Spacer()
  Text("Right")
}
Adds default padding around the text on all sides.
iOS Swift
Text("Hello")
  .padding()
Adds 20 points of padding only on the left side of the text.
iOS Swift
Text("Hello")
  .padding(.leading, 20)
This pushes "Top" text to the top and "Bottom" text to the bottom with space in between.
iOS Swift
VStack {
  Text("Top")
  Spacer()
  Text("Bottom")
}
Sample App

This app screen shows a yellow box with "Hello, SwiftUI!" text padded all around by 30 points. Below it, a green tinted horizontal row has "Left" text on the left and "Right" text on the right with space in between. The whole screen has some padding so content does not touch edges.

iOS Swift
import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Hello, SwiftUI!")
        .padding(.all, 30)
        .background(Color.yellow)
      Spacer()
      HStack {
        Text("Left")
        Spacer()
        Text("Right")
      }
      .padding(.horizontal, 20)
      .background(Color.green.opacity(0.3))
    }
    .padding()
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
OutputSuccess
Important Notes

Spacer only works inside stacks (HStack, VStack, ZStack) to push views apart.

Padding can be added to any view to create space inside its border.

Use padding and spacer together to create clean, balanced layouts.

Summary

Spacer creates flexible empty space inside stacks.

Padding adds fixed space around a view.

Use them to control layout spacing and improve app look and feel.