Consider this SwiftUI code defining a custom modifier and applying it to a Text view. What will the text look like?
struct Highlight: ViewModifier {
func body(content: Content) -> some View {
content
.padding(10)
.background(Color.yellow)
.cornerRadius(8)
}
}
Text("Hello SwiftUI")
.modifier(Highlight())Look at the order of modifiers inside the body function.
The Highlight modifier adds padding, then a yellow background, then rounds corners. So the text is padded inside a yellow rounded rectangle.
In SwiftUI, when does the body(content:) method of a ViewModifier get executed?
Think about how SwiftUI updates views reactively.
The body(content:) method is called whenever SwiftUI recomputes the view's body, which happens on state changes or environment updates.
Choose the correct Swift code for a ViewModifier that takes a Color parameter to set the background color.
Remember the body method signature and how to use parameters in structs.
Option A correctly declares a stored property color and uses it inside body. The method returns some View. Option A wrongly adds a parameter to body. Option A returns View instead of some View. Option A uses Color type instead of the variable color.
Given this code, why does the app crash when applying the modifier?
struct CrashModifier: ViewModifier {
func body(content: Content) -> some View {
content
.background(nil)
}
}
Text("Crash")
.modifier(CrashModifier())Check the parameter type for the background modifier.
The background modifier expects a View as parameter. Passing nil is invalid and causes a crash.
Which of these best explains why you would create a custom ViewModifier?
Think about code reuse and consistency in UI design.
Custom ViewModifiers let you package styling and behavior to apply consistently to many views, improving code reuse and clarity.