George Nhari
Code with C4

Follow

Code with C4

Follow
How can I provide two different fonts to a text based on the current Locale in SwiftUI?

Photo by Brett Jordan on Unsplash

How can I provide two different fonts to a text based on the current Locale in SwiftUI?

George Nhari's photo
George Nhari
ยทJan 8, 2023ยท

1 min read

Play this article

You can use the .font() modifier to set the font of a text view in SwiftUI. If you want to use different fonts depending on the current locale, you can use the .environment(\.locale) modifier to get the current locale, and then use an if statement or a switch statement to choose the appropriate font based on the locale.

For example:

Text("Hello")
  .font(.system(size: 20))
  .environment(\.locale) { locale in
    if locale == Locale(identifier: "fr_FR") {
      return Font.custom("Avenir", size: 20)
    } else {
      return Font.custom("Helvetica", size: 20)
    }
  }

This will use the "Avenir" font for French locales, and the "Helvetica" font for all other locales.

ย 
Share this