What’s the equivalent to String.localizedStringWithFormat(_:_:) for SwiftUI's LocalizedStringKey?

后端 未结 1 498
悲&欢浪女
悲&欢浪女 2021-02-14 12:19

What’s the equivalent to String.localizedStringWithFormat(_:_:) in SwiftUI?

I know LocalizedStringKey.init(:) can make use of string interpolat

相关标签:
1条回答
  • 2021-02-14 12:31

    I faced this issue as well and thanks to some sources and links I think I got it working the expected way.

    I was working on XCode12 Beta 6 when I succeeded, I can not confirm/infirm on other versions.

    The translation key needs to reflect the interpolated string you'll use in SwiftUI in which every argument is replaced by the String Format specifier representing the type of the argument.

    In your example, you want to insert one String as parameter. This corresponds to the %@ specifier.

    Rewrite your Localizable.strings by:

    "HELLO_WORLD" = "Hello, world!";
    "HELLO_WORLD_PARAMETERIZED %@" = "Hello, %@!";
    

    To use it inside a Text:

    Text("HELLO_WORLD_PARAMETERIZED \(someStringVar)")
    

    If you want to use a UInt parameter, use the %llu identifier, %lld for Int (see the String Format specifier link)

    The same rules apply for .stringdict, name the key using the same pattern:

    <dict>
        <key>%llu elements</key>
        <dict>
            <key>NSStringLocalizedFormatKey</key>
            <string>%#@VARIABLE@</string>
            <key>VARIABLE</key>
            <dict>
                <key>NSStringFormatSpecTypeKey</key>
                <string>NSStringPluralRuleType</string>
                <key>NSStringFormatValueTypeKey</key>
                <string>llu</string>
                <key>zero</key>
                <string>No elements</string>
                <key>one</key>
                <string>One element</string>
                <key>other</key>
                <string>%llu elements</string>
            </dict>
        </dict>
    </dict>
    </plist>
    

    To use the key:

    Text("\(someUIntVarValue) elements")
    
    0 讨论(0)
提交回复
热议问题