Member-only story

SwiftUI T-2

  1. how to create a reusable component in swiftUI

How to create reusable component in swiftUI

Creating reusable components in SwiftUI involves breaking down your UI into modular, self-contained views that can be reused across your app.

1. Basic Reusable Component

Create a custom view struct that encapsulates reusable UI elements.

Example: Custom Button

struct PrimaryButton: View {
let title: String
let action: () -> Void

var body: some View {
Button(action: action) {
Text(title)
.font(.headline)
.padding()
.frame(maxWidth: .infinity)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}

// Usage
PrimaryButton(title: "Submit") {
print("Button tapped!")
}

2. Flexible Content with @ViewBuilder

Allow your component to accept any child content using@ViewBuilder.
A custom attribute provided by SwiftUI to construct views using closures.

Example: Reusable Card

struct CardView<Content: View>: View {
let content: Content

init(@ViewBuilder content: () -> Content) {
self.content = content()
}

var body: some View {
VStack {
content
}
.padding()…

--

--

No responses yet