Coding With Amit
← Back to Articles

Building Reusable SwiftUI Components

Amit Sen

iOS engineer and educator. Helping developers build real-world skills.

Building Reusable SwiftUI Components

Reusable components save time and keep your UI consistent. Here's how to design them well.

Start with a Clear API

struct PrimaryButton: View {
    let title: String
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.headline)
                .frame(maxWidth: .infinity)
                .padding()
        }
        .buttonStyle(.borderedProminent)
    }
}

Use ViewBuilder for Flexibility

struct Card<Content: View>: View {
    @ViewBuilder let content: () -> Content
    
    var body: some View {
        VStack(alignment: .leading) {
            content()
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
}

Extract Modifiers

Create custom modifiers for repeated styling:

extension View {
    func cardStyle() -> some View {
        self
            .padding()
            .background(Color(.systemBackground))
            .cornerRadius(12)
    }
}

Document Your Components

Add a brief doc comment so your future self (and teammates) understand when to use each component.


Learn more SwiftUI patterns in our course.

Building Reusable SwiftUI Components | Coding With Amit