Create a custom bundle in the documents directory.
Looking at the Apple documentation for Text:
https://developer.apple.com/documentation/swiftui/text
The SwiftUI text view initializer accepts a bundle
parameter.
1 - We need to create a custom bundle. This can be done using the convenience initializer with a URL to our custom bundle:
convenience init?(url: URL)
https://developer.apple.com/documentation/foundation/bundle/1409352-init
2 - place programmatically the language folders in it ( and add the strings files inside).
The languages available on device can be found in:
Bundle.main.localizations
. which returns an array such as:
["de", "en", "Base", "en-US", "de-DE"]
You need to take this array and create the corresponding folders "de.proj", "en.proj" etc. in your custom bundle.
Then add the .strings
files with the key - translated value pairs such as ex in en.proj
the assets.strings
with:
`"Titlekey54" = "Localised title English";
This will show "Localised title English" in your UI if you selected English in settings and you passed the correct bundle to the Text
initializer.
NB: If you pass a variable you need to pass a LocalizedStringKey type or it will not localise automatically
(from the apple docs)
// a string variable will not be localized
Text(writingImplement)
// ...unless you explicitly convert it to a localized string key.
Text(LocalizedStringKey(writingImplement))
In this case I created a class to hold the current custom bundle and a setter to change it when the user changes language in the app.
The code to create the directories is a bit complicated and I don't want to make this post too long.
I will try to make my code available later on.
I made it to work in this small prototype app:
https://github.com/multitudes/MyLocalisationTestApp
Also, to create custom bundles on disk I found some good resource in this repo. 👍🏻
https://github.com/bharathi91/NextLevelLocalization