Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement localization in Swift UI

Can anybody help me? I can't find any description of the localization in Swift UI. Can anyone please give advice or better an example of how to localize for example Text()?

like image 778
Oleh H Avatar asked Oct 27 '19 10:10

Oleh H


People also ask

How do you do localization in SwiftUI?

Use it in custom SwiftUI views to make them ready for localization. Enable the "Use Compiler to Extract Swift Strings" build setting to extract LocalizedStringKeys from code when exporting for localization in Xcode. Format your strings to internationalize your code, and style them with Markdown.

How do I get localized string in SwiftUI?

In your project settings, go to Build Settings and search for Use compiler to Extract Swift Strings. Make sure to search All settings, not just the Basic ones. Change the value of this setting to Yes. In Xcode, go to Product ▸ Export Localizations….

What is localized in Swift?

Localization is the process of making your app support other languages. In many cases, you make your app with English user interface first and then localize the app to other languages such as Japanese. The process of localization is tedious, and steps of it change little by little as XCode gets updated.


Video Answer


1 Answers

When you look at documentation for Text you can see that it takes LocalizedStringKey not a String into its initializer:

init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil) 

It makes localizing very straightforward. All you have to do is:

  • create a new file of type "Strings File", call it Localizable.strings
  • select the new file and navigate to File Inspector in the right hand side panel and click Localize...
  • go to your project file to the Localizations section and add another language to the list - Xcode will create localization files for you

When you select you Localizable.strings you will see that it contains files for the original language and the language you have just added. That's where you put your translations, i.e. key - localized text pairs.

If you have a text like this is your app:

Text("Hello World!") 

You have to now add to your Localizable.strings your translations:

for your base language:

"Hello World!" = "Hello World!"; 

and for your second language (in this case German):

"Hello World!" = "Hallo Welt!"; 

To see your previews localised you can define them like this:

struct ContentViewView_Previews: PreviewProvider {      static var previews: some View {         ForEach(["en", "de"], id: \.self) { id in             ContentView()                 .environment(\.locale, .init(identifier: id))         }     } } 
like image 54
LuLuGaGa Avatar answered Sep 27 '22 23:09

LuLuGaGa