How to Style Views in SwiftUI: Simple Guide with Examples
In SwiftUI, you style views by applying
modifiers directly to the view, such as .background(), .cornerRadius(), and .shadow(). These modifiers change the appearance and layout of the view in a clear, readable way.Syntax
SwiftUI uses modifiers to style views. You write the view first, then chain styling methods after it. Each modifier returns a new view with the style applied.
Common modifiers include:
background(Color)- sets the background colorcornerRadius(CGFloat)- rounds the cornersshadow(radius: CGFloat)- adds shadowpadding()- adds space inside the view edges
swift
Text("Hello SwiftUI") .padding() .background(Color.blue) .cornerRadius(10) .shadow(radius: 5)
Output
A text label with blue background, rounded corners, shadow, and padding around the text.
Example
This example shows a styled button with padding, background color, rounded corners, and shadow. It demonstrates how easy it is to chain modifiers for styling.
swift
import SwiftUI struct ContentView: View { var body: some View { Button("Tap Me") { print("Button tapped") } .padding() .background(Color.green) .foregroundColor(.white) .cornerRadius(12) .shadow(color: .gray, radius: 4, x: 2, y: 2) } }
Output
A green rounded button with white text and a subtle shadow that prints a message when tapped.
Common Pitfalls
Some common mistakes when styling views in SwiftUI include:
- Applying modifiers in the wrong order, which can change the final look.
- Forgetting to set
foregroundColorfor text, making it hard to see on colored backgrounds. - Using
backgroundbeforepadding, which can cause the background to be too small.
Always remember that modifiers are applied in order, so the sequence matters.
swift
Text("Hello") .background(Color.yellow) .padding() // Background only covers text, not padding area // Correct order: Text("Hello") .padding() .background(Color.yellow) // Background covers text plus padding
Output
First text has yellow background only behind text. Second text has yellow background behind text and padding area.
Quick Reference
| Modifier | Purpose | Example |
|---|---|---|
| .padding() | Adds space inside view edges | Text("Hi").padding() |
| .background(Color) | Sets background color or view | Text("Hi").background(Color.red) |
| .cornerRadius(CGFloat) | Rounds corners of view | Text("Hi").cornerRadius(8) |
| .shadow(radius: CGFloat) | Adds shadow effect | Text("Hi").shadow(radius: 5) |
| .foregroundColor(Color) | Sets text or foreground color | Text("Hi").foregroundColor(.white) |
Key Takeaways
Use SwiftUI modifiers chained after a view to style it clearly and declaratively.
Modifier order matters; apply padding before background to cover the padded area.
Common styling includes background color, corner radius, shadow, padding, and foreground color.
Test your styles on different backgrounds to ensure text remains readable.
SwiftUI styling is simple and composable, making UI design fast and flexible.