How we can define a constant swiftUI-Type Font in SwiftUI?

Viewed 305

I can define a constant Font in UIKIt with this code:

let appFont = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)

And as you know we can use fonts in SwiftUI like this:

.font(.system(size: 35, weight: .ultraLight, design: .rounded))

now I like to make a constant of this code as appFont and call this code with just using .appFont, how we can do that?

2 Answers

If I correctly understood your needs, this can be done by extension to View, like

extension View {
    func appFont() -> some View {
        self.font(.system(size: 35, weight: .ultraLight, design: .rounded))
    }
}

so anywhere in your views you can use it as

var body: some view {
   SomeView().appFont()
}

You can declare your Font in an extension:

extension Font {

    static let appFont = Font.system(size: 18, weight: .regular)
}

and then use it like this:

Text("Example")
    .font(.appFont)
Related