How to localize iOS, VisionOS MacOS, TVOS & WatchOS apps in SwiftUI
A step by step tutorial describing our method for creating multilingual apps in SwiftUI. Github repository included.
The following tutorial is based on our localization tutorial for Swift and has been adapted to work with SwiftUI, previews and a custom macro that we coded to save hours of time when developing localizable content.
Please consult the posts below to learn about the way this was initially setup, how to create localizable previews as well as how the custom macro works.
The example can be found on the main branch of our SwiftUI Open Source Starter Project linked below.
The key differences from our Swift example are the following:
UIContent
Without the StringJSONMacros
With the StringJSONMacros
UIContent now uses @StringJSON macros to write initializers and variables, saving hours of time.
The StringJSON macros have been tested so they only works within the specific conditions that are required - the test cases and errors that are produced can be found within the StringJSONMacro folder of our project.
To learn more, consult the links below.
LanguageCoordinator
We have made the languageCode a constant for the application, which is set at the initializer.
The initializer has been updated to include an languageCode parameter to allow for Swift Previews to set the locale.
Separately:
- The coordinator is no longer a singleton as we are using it as an environment variable.
- The coordinator uses the @Observable macro, meaning it no longer requires notifications as SwiftUI manages this for us.
- The availableLanguages have been made public so that they are accessible to SwiftUI previews.
To learn more, consult the links below.
SampleScreen
We are now using a SampleScreen View struct instead of the CustomUIView.
Other changes include:
- This struct takes in a LanguageCoordinator environment variable.
- The strings are no longer optional, as the StringJSON macros create the necesary structure to remove this functionality.
- We no longer need notifications as SwiftUI manages this for us.
- There are previews for English and Spanish available. This was achieved by passing the language code to the environment variable for each preview.
How do I add it to Swift Testing?
Follow our guide linked below to get the LanguageCoordinator working with Swift Testing.
Looking to learn more about SwiftUI, Swift, Design and Technology?
Search our blog to learn more about Swift, SwiftUI, design and technology.