After building dozens of iOS apps with SwiftUI, I've collected some tips that dramatically improved my code quality. Here are 5 techniques I use in every project.
1. Use ViewModifiers for Reusable Styles
Instead of repeating the same modifiers, create a custom ViewModifier:
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 Subviews Early
Large views become unreadable fast. Extract components even if used only once:
struct ProfileView: View {
var body: some View {
VStack {
ProfileHeader()
ProfileStats()
ProfileActions()
}
}
}
3. Use @ViewBuilder for Conditional Content
@ViewBuilder
var content: some View {
if isLoggedIn {
HomeView()
} else {
LoginView()
}
}
4. Create Type-Safe Spacing Constants
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. Use Preview Providers Effectively
struct ButtonView_Previews: PreviewProvider {
static var previews: some View {
Group {
ButtonView(title: "Normal")
ButtonView(title: "Dark")
.preferredColorScheme(.dark)
}
}
}
Bonus: Get a Head Start
If you want a project with all these patterns ready to go, check out my SwiftUI Starter Kit Pro — it saves 40+ hours per project.
What tips do you use? Drop them in the comments!
Follow @SwiftUIDaily for more iOS content.
Top comments (0)