Can You Write a Custom View Modifier?
A custom view modifier is how you turn a repeated SwiftUI style into a named, reusable API — and that’s exactly what this interview…
Can You Write a Custom View Modifier?
A custom view modifier is how you turn a repeated SwiftUI style into a named, reusable API — and that’s exactly what this interview question is probing.
This one shows up often enough in SwiftUI interviews that it’s worth having ready. It’s not a trick question. When it does come up, interviewers usually want a quick signal: can you move past .padding().background(.red) pasted on every screen, and actually name that look?
Most candidates know modifiers exist. Fewer can build one cleanly under pressure.
What a strong answer looks like
You’re expected to:
- Conform to
ViewModifier - Style
contentinsidebody - Expose a
Viewextension so usage reads like a built-in modifier - Explain why — reuse, clarity, one place to change
The code
import SwiftUI
struct PaddedRedBackground: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.red)
}
}
extension View {
func paddedRedBackground() -> some View {
modifier(PaddedRedBackground())
}
}
struct Parent: View {
var body: some View {
Text("Hello World")
.paddedRedBackground()
}
}
The extension lets you call .paddedRedBackground() instead of typing .modifier(PaddedRedBackground()) every time — so it feels like a normal SwiftUI modifier.
메타데이터
- post_id
- 1054faf321d2
- slug
- can-you-write-a-custom-view-modifier-1054faf321d2
- url
- https://medium.com/@gaganjoshi.dev/can-you-write-a-custom-view-modifier-1054faf321d2
- canonical_url
- https://medium.com/@gaganjoshi.dev/can-you-write-a-custom-view-modifier-1054faf321d2
- author_url
- https://medium.com/@gaganjoshi.dev
- status
- ok
- fetched_at
- 2026-08-08 00:02:55