1

Is there a way to build a view modifier that applies custom font and fontSize, as the below working example, and have in the same modifier the possibility to add kerning as well?

struct labelTextModifier: ViewModifier {
    var fontSize: CGFloat

    func body(content: Content) -> some View {
        content
            .font(.custom(Constants.defaultLabelFontSFProDisplayThin, size: fontSize))
    }
}

extension View {   
    func applyLabelFont(size: CGFloat) -> some View {
        return self.modifier(labelTextModifier(fontSize: size))
    }
}

The above works well, however i cannot figure it out how to add kerning to the modifier as well

tried

content
    .kerning(4)

, but did not work.

Suggestions?

Dan
  • 151
  • 3
  • 12
  • `.kerning` is Text-only specific modifier (in opposite to `.font`) and you cannot use it with generic `ViewModifier`. – Asperi Dec 16 '19 at 13:03
  • @Asperi, thanks for your answer! So the only way to do it is just to apply it on each Text in the views and not use the generic ViewModifier, got it right? – Dan Dec 16 '19 at 13:52
  • Right. With your custom modifier it would be like `Text("test").kerning(4).applyLabelFont(14.0)` – Asperi Dec 16 '19 at 13:55

1 Answers1

3

Alternate is to use Text-only modifier, like

extension Text {   
    func applyLabelFont(size: CGFloat, kerning: CGFloat = 4) -> Text {
        self
          .font(.custom(Constants.defaultLabelFontSFProDisplayThin, size: size))
          .kerning(kerning)
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690