25
loading...
This website collects cookies to deliver better user experience
Localizable.strings
file where we put all the translations. I’m not going into how to create this for your projects.Text
, Button
, TextField
, and more come with initializers using localization behind the scenes.Text
view with the title Name
. We can add that to the Localizable.strings
file and it would be translated without us doing anything. If the translation isn’t provided, it will fall back to the specified default title. We can say that SwiftUI takes care of translating our apps without us doing extra work.Text
initializer.init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)
LocalizedStringKey
. Let’s explore it.LocalizedStringKey
is the magic that powers all the translations in our SwiftUI apps. What it does is looks up in the Localizable.strings
file and checks if there is a translation with this key. It conforms to ExpressibleByStringLiteral
and that’s why we can use it in our SwiftUI view initializers.LocalizedStringKey
is when a translation is passed into the view. Let’s say we have a greetings view that takes in a greeting text as a parameter. In such a case, we need to create a parameter that has type LocalizedStringKey
. When constructing this, we pass in not the String
value but initialized LocalizedStringKey
by using the LocalizedStringKey(_ value: String)
initializer. In this case, it isn’t treated as just text, but a key from the translations strings file.Hello, Mary!
, but Mary
would be substituted with an entry from the text field. To translate this kind of text, we should use string interpolation.Localizable.strings
file entry Hello, %@!
and the %@
would be a String
parameter we pass in when creating the LocalizedStringKey
like this:Text("Hello, \(name)!")
Localizable.strings
file.