Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to add custom modifier for Text

Tags:

ios

swift

swiftui

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: 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?

like image 407
Rodrigo Mata Avatar asked Jul 05 '19 16:07

Rodrigo Mata


2 Answers

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().

like image 179
Valerika Avatar answered Sep 19 '22 14:09

Valerika


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())
like image 40
kontiki Avatar answered Sep 21 '22 14:09

kontiki