Home > Software design >  how to localize a picker to another language?
how to localize a picker to another language?

Time:03-02

@State var selectedSpace : FreeSpace = .Big_Bag

     Picker("", selection: $selectedSpace) {
                            ForEach(FreeSpace.allCases) { FreeSpace in
                                Text(FreeSpace.rawValue.capitalized)
                            }
                        }.environment(\.locale, Locale.init(identifier: "az-Arab"))
                          .foregroundColor(Color("Color"))
                          .padding(.trailing)

Knowing that the pickerValues

enum FreeSpace: String, CaseIterable, Identifiable {
        case Big_Bag, Small_Bag
        var id: Self { self }
    }

i'm trying to convert what is inside the picker to arabic and can't find a solution it is always displayed in english.

CodePudding user response:

From apple doc :

If you intialize a text view with a variable value, the view uses the init(:) initializer, which doesn’t localize the string. However, you can request localization by creating a LocalizedStringKey instance first, which triggers the init(:tableName:bundle:comment:) initializer instead:

// Don't localize a string variable...
Text(writingImplement)

// ...unless you explicitly convert it to a localized string key.
Text(LocalizedStringKey(writingImplement))

That means that you must use :

Text(LocalizedStringKey(FreeSpace.rawValue.capitalized))

CodePudding user response:

I think you misunderstood the concept of iOS localization. In you app you need to provide localizable strings file (usually it is named Localizable.strings), which holds localization values for your supported languages.

So basically in your project settings, you need to enable desired languages (English and Arabic on the screenshot). languages

Then you create Localizable.strings file and add it as a resource of your app. Then just make it localizable by clicking localize in File Inspector.

localizable button

This will let you choose what language you want to use for the current file. Once you make it localizable you can tick what languages to use and you can switch them in Project Navigator.

localized files

Since now you will put localized texts in its appropriate Localizable file and use its key to access it.

Then if you use Text(String(localized: "key").uppercased()) you should be fine.

  • Related