So far, I am able to write custom modifiers for Views; however, when trying to keep my code DRY, I am trying to add a custom modifier for TextFields. The view modifiers work great with something like so:
struct sampleModifier : ViewModifier {
var height: CGFloat? = 100
func body(content: Content) -> some View {
content
.frame(height: height)
.background(Color.white)
.border(Color.gray, width: 0.5)
.shadow(color: Color.black, radius: 15, x: 0, y: 10)
}
}
But when I try to use modifiers like font
and so, it shows a lot of errors. I do understand that they might need to be more specific and instead conform to the TextFieldStyleModifier
, but I do not get how to make it work. I have tried to do it this way without success:
struct TitleModifier : TextFieldStyleModifier {
func body(content: TextFieldStyle) -> some View {
content
.font(.custom("Open Sans", size: 18))
.color(Color.green)
}
}
Which obviously fails and shows the following error:
If I click on the Fix
suggestion, it adds this to my code
TextFieldStyleModifier<<#Style: TextFieldStyle#>>
Which I do not know how to use.
Any suggestions?
Right now it is possible to add .font()
and .foregroundColor()
modifiers to the content
inside ViewModifier. However, if you want to add some custom modifiers that can be applied only to a specific view, for example .strikethrough()
modifier for Text View, you can add these modifiers into the extension.
struct TitleModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.custom("Open Sans", size: 18))
.foregroundColor(.green)
}
}
extension Text {
func customText() -> some View {
self.strikethrough().bold().italic().lineLimit(4)
.modifier(TitleModifier())
}
}
Usage Text("Hello").customText()
.
TextFields are also views, so you create the modifier in the same fashion:
struct TitleModifier : ViewModifier {
func body(content: Content) -> some View {
content
.font(.custom("Open Sans", size: 18))
.foregroundColor(Color.green)
}
}
Also note that there is no modifier .color(). It is .foregroundColor().
When you want to apply it to a FormField, you just do:
TextField("", text: $field1).modifier(TitleModifier())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With