Home > Blockchain >  SwiftUI Text doesn't localise when inside ForEach
SwiftUI Text doesn't localise when inside ForEach

Time:09-16

When my Text gets it's string from an array, it doesn't localise, but when I hard-code it in, it does:

Localizable.strings

"greeting1" = "Hello there";
"greeting2" = "Howdy";

(Localised into English)

My View

var localisedStrings = ["greeting1", "greeting2"]

struct Message: View {
    var body: some View {
        ForEach(localisedStrings, id: \.self) { string in
            Text(string)
        }
    }
}

The text will just write the key, like "greeting1", rather than "Hello there"

Is there a way to force the Text object to use a localised string? Or is it changing somehow because it's getting it's content from a ForEach loop?

My View (hard coded)

//var localisedStrings = ["greeting1", "greeting2"]

struct Message: View {
    var body: some View {
        //ForEach(localisedStrings, id: \.self) { string in
            Text("greeting1")
        //}
    }
}

This works just fine, and results in the text displaying "Hello there".

CodePudding user response:

It works when you hardcode the string in, because you are using this initialiser, which takes a LocalizedStringKey.

LocalizedStringKey is ExpressibleByStringLiteral, but the word string in Text(string) is not a "string literal", so it calls this initialiser instead, and is not localised. You can initialise an instance of LocalizedStringKey directly, in order to localise it:

Text(LocalizedStringKey(string))

CodePudding user response:

It's because here you are using plain String Swift type

var localisedStrings = ["greeting1", "greeting2"]

and here you are using SwiftUI own LocalizedStringKey type

Text("greeting1")

To fix your issue map your string to LocalizedStringKey

struct Message: View {
    var body: some View {
        ForEach(localisedStrings, id: \.self) { string in
            Text(LocalizedStringKey(string))
        }
    }
}

Text.init(_:tableName:bundle:comment:)

Please follow the linked documentation to learn more.

  • Related