SwiftUI — Three Common Use Cases Of ViewModifier

Imad Ali Mohammad
2 min readApr 18, 2023

--

SwiftUI’s ViewModifier the protocol allows you to create reusable pieces of functionality that can be applied to multiple views, making it a powerful tool for organizing and simplifying your code. By creating custom view modifiers, you can abstract away common functionality, such as padding or styling, and apply it to multiple views in a consistent and easy-to-maintain way.

#1 One common use case for view modifiers is applying a consistent style or theme to multiple views. For example, you could create a custom view modifier that sets the font, color, and background color of a view, and then apply it to multiple text views throughout your app to ensure a consistent style.

struct TitleModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.largeTitle)
.foregroundColor(.white)
.background(Color.blue)
}
}
Text("My Title")
.modifier(TitleModifier())

#2 Another use case of viewModifier is adjusting padding or spacing. By creating a view modifier that adds padding or spacing to a view, you can avoid having to manually adjust the padding or spacing of multiple views in your app, and instead apply the same functionality in a consistent way.

struct PaddingModifier: ViewModifier {
let padding: CGFloat

func body(content: Content) -> some View {
content
.padding(padding)
}
}

VStack {
Image("MyImage")
.modifier(PaddingModifier(padding: 10))

Text("My Description")
.modifier(PaddingModifier(padding: 10))
}

#3 Another use case for view modifiers is adding a custom behavior or logic to your views. For example, you could create a view modifier that changes the text color of a view when it is tapped, allowing you to easily add this functionality to multiple views throughout your app.

struct HighlightModifier: ViewModifier {
@State private var isHighlighted = false

func body(content: Content) -> some View {
content
.foregroundColor(isHighlighted ? .yellow : .primary)
.onTapGesture {
self.isHighlighted.toggle()
}
}
}

Text("Tap Me")
.modifier(HighlightModifier())

In summary, viewModifiers in SwiftUI can help to abstract away common functionality and apply it to multiple views in a consistent and easy-to-maintain way, whether it’s styling, padding, behavior, or logic. They are the building blocks of reusable, composable, and maintainable view components in SwiftUI.

--

--

Imad Ali Mohammad
Imad Ali Mohammad

Written by Imad Ali Mohammad

Senior iOS Engineer, Passionate about coding and building amazing apps.

No responses yet