How do I build reusable views and view modifiers?

In SwiftUI, creating reusable views and view modifiers is essential for maintaining clean and succinct code. Reusable views help in reducing redundancy and improving code clarity, while custom view modifiers can encapsulate styling and behavior that can be reused across multiple components.

Creating a Reusable View

To create a reusable view, define a `struct` that conforms to the `View` protocol. Here's an example of a reusable button component:

struct CustomButton: View { var title: String var action: () -> Void var body: some View { Button(action: action) { Text(title) .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } } }

Using the Reusable View

You can easily use the `CustomButton` view in your main view:

struct ContentView: View { var body: some View { VStack { CustomButton(title: "Click Me", action: { print("Button tapped!") }) CustomButton(title: "Another Button", action: { print("Another button tapped!") }) } } }

Creating a Custom View Modifier

Custom modifiers can be created by defining a new `ViewModifier`. Here's how you can create a simple modifier for adding padding and a background color:

struct RoundedBackground: ViewModifier { func body(content: Content) -> some View { content .padding() .background(Color.gray.opacity(0.2)) .cornerRadius(10) } } extension View { func roundedBackground() -> some View { self.modifier(RoundedBackground()) } }

Using the Custom View Modifier

Apply the custom modifier to your views easily:

struct ExampleView: View { var body: some View { VStack { Text("Hello, World!") .roundedBackground() Text("Goodbye, World!") .roundedBackground() } } }

SwiftUI reusable views view modifiers custom views Swift programming SwiftUI development