SwiftUI: Previewing localized text in the canvas

monicag

Monica Granbois

Posted on June 29, 2020

 SwiftUI: Previewing localized text in the canvas

Last week I watched the Swift packages: Resources and localization video from WWDC20. One thing I learned was that the Canvas can preview localized values. This is done by adding a locale to a View via the environment.

Example:

import SwiftUI

struct ContentView: View {
    var body: some View {
       Text("greeting")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.locale, Locale.init(identifier: "fr"))
    }
}

Enter fullscreen mode Exit fullscreen mode

The above code assumes that a French Localizable.strings file exist with a greeting key. For example:

"greeting" = "Bonjour le monde!";
Enter fullscreen mode Exit fullscreen mode

The EnvironmentValues documentation lists all the values that can be set.

Gif showing the Canvas preview switching greeting text between english, french and german.

💖 💪 🙅 🚩
monicag
Monica Granbois

Posted on June 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related