June 28, 2019

Localization in SwiftUI

Learn how to localize your SwiftUI app into multiple languages and preview it in the live view, all without running your app in the simulator.

Localization in SwiftUI

Localization is the process of making your app support other languages.  In this blog post, I'm going to teach you how to localize your SwiftUI app.

After WWDC19 I started experimenting with SwiftUI and how it works, as it turns out, there isn't much documentation about any specific feature so I thought I'd take a stab at the problem and try to write a useful tutorial to help beginners learn how to localize their app.

Creating a .strings file

To add  localizations we'll need a .strings file. To create one, do Command-N , and click on "Strings File". Name the file Localizable and hit "Create".

Now open Localizable.strings and in the right pane and click "Localize"

Creating localization files

Now that we have a .strings file that is setup for localization, we can add it to our project. Open the project navigator and select your project from the sidebar. Under "Localizations" click + and select the locale you want to add (in this post, we'll be using French).

A popup should appear. Make sure both items are checked and click "Finish".

If you only see LaunchScreen.storyboard in the popup something has went wrong and you may want to take another look at your project.

Localizing your app

Before we start localizing , you should familiarize yourself with the .strings syntax. Transifex has an awesome help doc with samples and more in-depth information about the .strings format. I recommend you check that out here.

Open  Localizable.strings (French)  and pase:

"hello_world" = "Bonjour le monde"; 

Then open Localizable.string (English) and paste:

"hello_world" = "Hello World"; 

Now open your ContentView.swift file and add Text("hello_world")  to the body.

Previewing localizations

One of the big appeals of SwiftUI is the ability to see changes to your UI instantly, without running them in the simulator. You can preview how you app will look in different locales by adding the  .environment(.locale, Locale(identifier: "<# locale identifier #>")) modifier to your preview.

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
                .environment(\.locale, Locale(identifier: "en"))
            ContentView()
                .environment(\.locale, Locale(identifier: "fr"))
        }
    }
}
#endif

Conclusion

Congrats, you localized you app and know how to preview it in different languages. Now whole new groups of people are now able to use your app.

If you have any feedback or comments feel free to tweet them to me at @nathfreder or send me an email at [email protected].