How to Use Padding Modifier in SwiftUI: Simple Guide
In SwiftUI, you use the
padding() modifier to add space around a view. You can call padding() without parameters for default spacing or specify edges and amount like padding(.leading, 20) to add 20 points of padding on the left side.Syntax
The padding() modifier adds space around a view. You can use it in three ways:
padding(): Adds default padding on all sides.padding(Edge.Set): Adds default padding on specified edges.padding(Edge.Set, CGFloat): Adds custom padding amount on specified edges.
swift
Text("Hello SwiftUI") .padding() Text("Hello SwiftUI") .padding(.horizontal) Text("Hello SwiftUI") .padding(.top, 30)
Example
This example shows a text view with padding on all sides and another with custom padding only on the top.
swift
import SwiftUI struct ContentView: View { var body: some View { VStack { Text("Hello with default padding") .padding() .background(Color.yellow) Text("Hello with 40 points top padding") .padding(.top, 40) .background(Color.green) } } }
Output
Two text views stacked vertically: the first has yellow background with space around all sides, the second has green background with extra space only above it.
Common Pitfalls
Beginners often forget that padding() adds space inside the view's background. Also, specifying edges incorrectly or mixing multiple padding modifiers can cause unexpected layouts.
Always check which edges you want to pad and avoid stacking multiple conflicting paddings.
swift
Text("Wrong padding") .padding(.leading, 20) .padding(.trailing, 40) .padding(.leading, 10) // This overrides the first leading padding Text("Correct padding") .padding([.leading, .trailing], 20)
Quick Reference
| Usage | Description |
|---|---|
| padding() | Adds default padding on all sides |
| padding(.all, 10) | Adds 10 points padding on all sides |
| padding(.horizontal) | Adds default padding on left and right |
| padding(.vertical, 15) | Adds 15 points padding on top and bottom |
| padding(.top, 20) | Adds 20 points padding on top only |
Key Takeaways
Use padding() to add space inside a view easily in SwiftUI.
Specify edges and amount to control padding precisely.
Avoid stacking multiple padding modifiers on the same edges.
Padding adds space inside the view's background area.
Use padding to improve layout spacing and readability.