2

I am trying to localize my app using this method: How to implement localization in Swift UI

In general it works. One problem I found is with text concatenation. Example: I have a translation for the text "bookings". To make it work I need to separate my previous code:

Text("bookings: 40")

to be:

Text("bookings")
    .fontWeight(.bold)
+ Text(": 40")
    .fontWeight(.bold)

Translation still works. The problem is that right now I need to have text formatting twice (in this example: fontWeight, but sometimes it's more complex).

I have tried to make it more simple like this:

Text("bookings" + ": 40)
    .fontWeight(.bold)

This code works in English, but is not being translated now to another languages. How should I change my code to make it work and keep it simple?

mallow
  • 2,368
  • 2
  • 22
  • 63

1 Answers1

6

Text localization works with string interpolation, see for example the WWDC 2019: What's new in Swift session video, or Localization in SwiftUI, or this answer.

However, you have to use the correct format specifier. For strings, it is %@, for integers it is %lld. Example:

let value = 40

struct ContentView: View {
    var body: some View {
        Text("bookings: \(value)")
            .fontWeight(.bold)
    }
}

with the localization entry

"bookings: %lld" = "Buchungen: %lld";

in the Localizable.strings file results in the text "Buchungen: 40" to be displayed in a bold font:

enter image description here

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks a lot! :) It works. However, I have changed the code slightly. `let stringValue = ": \(value)"` and then I just translate `"bookings%@" = "Buchungen%@";`. This way I am keeping this order of label: value – mallow Nov 25 '19 at 06:45
  • @mallow: You are welcome. – But actually my statement *“you have to convert the integer to a string first”* was wrong, I have updated the answer accordingly. – Martin R Nov 25 '19 at 07:53
  • Anyone except me experiencing no success with any of the "%lld" or "%@" techniques I have seen here or elsewhere? XCode 11.4 b3. – HelloTimo Mar 17 '20 at 14:17
  • @HelloTimo: I worked for me when I wrote the answer – the screenshot is not a fake :) – Martin R Mar 17 '20 at 14:44
  • @MartinR No doubt. Maybe a current beta bug. – HelloTimo Mar 17 '20 at 15:32
  • I'm not sure if anyone else facing the issue that using %@ or %d don't localize concat-ed strings? I'm facing this issue iOS 13.3 XCode 11.3.1 – Benzamin Apr 05 '20 at 12:37