Spacer and padding help you control space and distance between things on the screen. They make your app look neat and easy to use.
Spacer and padding in 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.
HStack {
Text("Left")
Spacer()
Text("Right")
}Text("Hello")
.padding()Text("Hello") .padding(.leading, 20)
VStack {
Text("Top")
Spacer()
Text("Bottom")
}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.
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() } }
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.
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.