简体   繁体   中英

How to use dynamic localization keys with SwiftUI

I'm trying to display a localized text based on an ID. I have a lot of these, so it feels more efficient to just add dynamically the ID to the string.

The string file looks like this:

"users.1.name" = "Alice"
"users.2.name" = "Bob"
"users.3.name" = "Charles"
...

If I do the following, hardcoding the ID, it works as expected and displays the associated translated key:

Text("users.1.name")

However if I do this it only displays the string:

Text("users.\(user.id).name")
// displays "users.1.name" instead of "Alice"

I've also tried:

Text(LocalizedStringKey("users.\(user.id).name"))
// displays "users.1.name" instead of "Alice"

Am I missing something or is this not possible?

You need then the following. Tested with Xcode 11.4 / iOS 13.4

Text(NSLocalizedString("users.\(id).name", comment: ""))

I'm not a SwiftUI expert but you can use:


let key:String = "users.\(user.id).name"
Text(LocalizedStringKey(key))

// OR compact

Text(LocalizedStringKey(String("users.\(user.id).name")))


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM