Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a simple custom ViewModifier named RedTitle that makes text red and bold.
iOS Swift
struct RedTitle: ViewModifier {
func body(content: Content) -> some View {
content
.foregroundColor([1])
.bold()
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using UIColor instead of Color for SwiftUI colors.
Trying to use .red without Color prefix.
✗ Incorrect
The correct way to set the text color in SwiftUI is using Color.red, not .red or UIColor.red.
2fill in blank
mediumComplete the code to apply the custom ViewModifier RedTitle to a Text view.
iOS Swift
Text("Hello World") .[1](RedTitle())
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .apply or .use which do not exist in SwiftUI.
Trying to call the modifier without parentheses.
✗ Incorrect
The correct method to apply a custom ViewModifier is .modifier().
3fill in blank
hardFix the error in the custom ViewModifier by completing the missing return type for the body function.
iOS Swift
struct BlueBackground: ViewModifier {
func body(content: Content) -> [1] {
content
.background(Color.blue)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning Void or Content instead of some View.
Omitting the return type.
✗ Incorrect
The body function must return some View to conform to ViewModifier protocol.
4fill in blank
hardFill both blanks to create a reusable ViewModifier named RoundedBorder that adds a rounded border with a given color and width.
iOS Swift
struct RoundedBorder: ViewModifier {
var color: Color
var width: CGFloat
func body(content: Content) -> some View {
content
.overlay(
RoundedRectangle(cornerRadius: [1])
.stroke(color, lineWidth: [2])
)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using very large corner radius or line width values.
Mixing up corner radius and line width values.
✗ Incorrect
A corner radius of 10 and line width of 5 create a nicely rounded border.
5fill in blank
hardFill all three blanks to create a View extension that applies the RoundedBorder modifier with default color and width.
iOS Swift
extension View {
func roundedBorder() -> some View {
self.modifier(RoundedBorder(color: [1], width: [2]))
}
func roundedBorder(color: Color, width: CGFloat) -> some View {
self.modifier(RoundedBorder(color: color, width: [3]))
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a literal number instead of the parameter in the second method.
Mixing up default color values.
✗ Incorrect
The default color is Color.black, default width is 3, and the second method uses the passed width parameter.