1

If I have this ViewModifier.

struct AppFont: ViewModifier {
var size: Int?
func body(content: Content) -> some View {
    content.font(Font.custom("Futura", size: CGFloat(size ?? 15)))
}

}

From that I create an extension one for Text and one for Textfield

 extension Text {
    func customFont(size : Int) ->  some View {
        return ModifiedContent(content: self, modifier: AppFont(size: size))
    }
}

extension TextField {
     func customFont(size : Int) ->  some View {
           return ModifiedContent(content: self, modifier: AppFont(size: size))
       }
}

How can I add this extension to Text, Textfield and Button without repeating the code? So I could use Text("hello").customFont() TextField(...).customFont() or Button().customFont()

1 Answer 1

1

There is not really anything to gain by wrapping the font in a custom ViewModifier and then again using it in an extension. I think the best solution is to have an extension on Text separately to have the return type be Text so you can apply other text-specific modifiers to it. You can also have an extension on View that will cover all other scenarios.

extension Text {

    func customFont(size : Int = 15) -> Text {

        return self.font(Font.custom("Futura",
                                     size: CGFloat(size)))
    }
}

extension View {

    func customFont(size : Int = 15) -> some View {

        return self.font(Font.custom("Futura",
                                     size: CGFloat(size)))
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.