A modifier does not change a view. It wraps it and returns a new one. Text("Hi").padding() is not a Text with padding set - it is a padding view containing a text view. Once you see it that way, the single most common SwiftUI confusion resolves itself: order matters, and it reads outwards.
.padding().background(.blue) puts padding round the text and then paints the background behind the padded thing, so the blue extends past the letters. .background(.blue).padding() paints behind the text only, then adds clear space round the coloured box. Same two modifiers, different pictures.
For colour and type, prefer the semantic options over fixed values. .foregroundStyle(.secondary) adapts to light and dark mode; Color(red:green:blue:) does not. .font(.headline) scales with the reader's Dynamic Type setting; .font(.system(size: 17)) ignores it and will get your app rejected in an accessibility review. The system styles are how an app made by one person looks like an app made by Apple.
When you find yourself repeating the same five modifiers, extract them into a ViewModifier and give the combination a name.
import SwiftUI
struct StyledButtons: View {
var body: some View {
VStack(spacing: 20) {
// Order matters: padding first, so the fill extends past the text.
Text("Padding, then background")
.padding(.horizontal, 20).padding(.vertical, 10)
.background(.tint, in: Capsule())
.foregroundStyle(.white)
// The other way round: background hugs the text, padding is clear.
Text("Background, then padding")
.background(.tint.opacity(0.2), in: Capsule())
.padding(.horizontal, 20).padding(.vertical, 10)
// A reusable combination, named once.
Text("Reusable").modifier(CardStyle())
}
.font(.headline) // semantic: scales with Dynamic Type
.padding()
}
}
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.frame(maxWidth: .infinity)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
.foregroundStyle(.primary) // adapts to light and dark
}
}
#Preview { StyledButtons() }