5 SwiftUI Tips That Will Make Your Code 10x Cleaner
Source: Dev.to
1. Create reusable ViewModifiers
Instead of repeating the same modifiers, define a custom ViewModifier and expose it via a view extension.
struct PrimaryButtonStyle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
extension View {
func primaryButtonStyle() -> some View {
modifier(PrimaryButtonStyle())
}
}
// Usage
Text("Hello")
.primaryButtonStyle()
2. Extract sub‑views even for single use
Large view bodies become hard to read quickly. Pull distinct parts into their own View structs.
struct ProfileView: View {
var body: some View {
VStack {
ProfileHeader()
ProfileStats()
ProfileActions()
}
}
}
3. Use @ViewBuilder for conditional content
Encapsulate branching UI logic in a computed property or function annotated with @ViewBuilder.
@ViewBuilder
var content: some View {
if isLoggedIn {
HomeView()
} else {
LoginView()
}
}
4. Centralize spacing values
Define a single source of truth for spacing constants to keep layouts consistent.
enum Spacing {
static let xs: CGFloat = 4
static let sm: CGFloat = 8
static let md: CGFloat = 16
static let lg: CGFloat = 24
}
VStack(spacing: Spacing.md) {
Text("Title")
}
5. Provide comprehensive previews
Show multiple variations of a view in the preview canvas, including dark‑mode support.
struct ButtonView_Previews: PreviewProvider {
static var previews: some View {
Group {
ButtonView(title: "Normal")
ButtonView(title: "Dark")
.preferredColorScheme(.dark)
}
}
}
Ready‑to‑use starter kit
If you’d like a project that already incorporates these patterns, check out the SwiftUI Starter Kit Pro – it can save dozens of hours per project.