Creating Reusable Components in SwiftUI: A Guide

Just like in design tools and React, SwiftUI is component-based. 

To keep your code clean and reusable, you should turn them into components. SwiftUI gives you the ability to Extract Subview. 

This allows you to turn complex code into smaller chunks of code which leads to the code looking more organized and easier to read.

How to create reusable components by using the Extract Subview option in SwiftUI

Extract Subview 

Extracting breaks down a larger, more complex piece of code into smaller parts. This improves the readability of the code while making it look more organized at the same time. 

  • Command + Click the element and select: Extract Subview. 
  • Once ExtractedView() appears, rename it to LargeButton.
struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Text("Swift UI IO")
                .font(.largeTitle).bold()
                .frame(maxWidth: .infinity, alignment: .leading)
            Text("A complete series of tutorials covering Xcode, and SwiftUI.")
            LargeButton()
            Spacer()
        }
        .padding(20)
    }
}
Please note that this option only appears when there's a parent container.
..
Customize with Variables 
You can pass variables to your component to make it more customizable.
struct LargeButton: View {
    var text = "Download files"

    var body: some View {
        Button(action: {}) {
            Text(text)
                .bold()
        }
        .frame(maxWidth: .infinity)
        .padding(12)
        .background(Color.blue)
        .foregroundColor(.white)
        .cornerRadius(12)
    }
}
If you the component's variables don't have default values, you'll need to pass the variables.
..
LargeButton(text: "Download")
..
Component as New File 
  • Ideally, you want to store each component in its separate file and organize them neatly into folders and subfolders. 
  • To avoid confusion, make sure that the name of the file is the same as the component name.
..

Comments