0
0
iOS Swiftmobile~5 mins

Custom ViewModifiers in iOS Swift

Choose your learning style9 modes available
Introduction

Custom ViewModifiers help you reuse style and behavior for views easily. They keep your code clean and consistent.

You want to apply the same style to many buttons in your app.
You need to add a common shadow and corner radius to multiple views.
You want to create a reusable animation effect for text fields.
You want to keep your UI code simple by grouping view changes.
You want to share a custom style across different screens.
Syntax
iOS Swift
struct MyModifier: ViewModifier {
  func body(content: Content) -> some View {
    content
      .modifier1()
      .modifier2()
  }
}

// Usage:
Text("Hello")
  .modifier(MyModifier())

The body function defines how the view looks after applying the modifier.

You use content to represent the original view inside the modifier.

Examples
This modifier makes text large and red.
iOS Swift
struct RedTitle: ViewModifier {
  func body(content: Content) -> some View {
    content
      .font(.title)
      .foregroundColor(.red)
  }
}

Text("Hello")
  .modifier(RedTitle())
This modifier adds padding, a light background, rounded corners, and shadow to a button.
iOS Swift
struct RoundedShadow: ViewModifier {
  func body(content: Content) -> some View {
    content
      .padding()
      .background(Color.gray.opacity(0.2))
      .cornerRadius(10)
      .shadow(radius: 5)
  }
}

Button("Tap Me") {
  print("Tapped")
}
.modifier(RoundedShadow())
Sample App

This app shows two texts. The first text uses the custom Highlight modifier to get padding, a yellow background, and rounded corners. The second text is normal.

iOS Swift
import SwiftUI

struct Highlight: ViewModifier {
  func body(content: Content) -> some View {
    content
      .padding(10)
      .background(Color.yellow)
      .cornerRadius(8)
  }
}

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      Text("Important Message")
        .modifier(Highlight())
      Text("Normal Text")
    }
    .padding()
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
OutputSuccess
Important Notes

You can add parameters to your custom ViewModifier to make it flexible.

Use .modifier() to apply your custom modifier to any view.

Custom modifiers help keep your UI code clean and reusable.

Summary

Custom ViewModifiers let you bundle view styles and behaviors.

They make your UI code easier to read and reuse.

Apply them with .modifier() on any SwiftUI view.