Search code examples
swiftswiftuiviewmodifier

SwiftUI ViewModifier - add kerning


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?


Solution

  • 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)
        }
    }