简体   繁体   English

SwiftUI 本地化不适用于 @State 字符串

[英]SwiftUI Localisation not working with @State Strings

I have implemented Localisation in my SwiftUI app.我已经在我的 SwiftUI 应用程序中实现了本地化。 Everything works fine but I'm having issues with localising @State var.一切正常,但我在本地化 @State var 时遇到问题。 Localisation is not working and I'm getting only the keys printed out.本地化不起作用,我只能打印出密钥。 Any idea how to fix this issue?知道如何解决这个问题吗?

The value of type is already in my Localizable.strings type的值已经在我的Localizable.strings

@State var type: String

var body: some View {
    VStack {
        Text(self.type) // not working
        Text("test") // working
    }
}

You can take convert the string into a NSLocalizedString您可以将字符串转换为NSLocalizedString

Text(NSLocalizedString(type, comment: ""))

or change the type of type into a LocalizedStringKey或将类型的type更改为LocalizedStringKey

@State var type: LocalizedStringKey

When a string literal is passed to Text its type needs to be inferred (Since it isn't explicitly stated).当将字符串文字传递给Text时,需要推断其类型(因为没有明确说明)。 Literal text is probably a fixed part of your UI, so it is interpreted as a LocalizedStringKey .文字文本可能是 UI 的固定部分,因此它被解释为LocalizedStringKey

When you pass the property self.type , it has an explicit type - String , so the Text(_ verbatim:) initialiser is used resulting in non-localised text.当您传递属性self.type时,它具有显式类型 - String ,因此使用Text(_ verbatim:)初始化程序会导致非本地化文本。

If you want that property to be localised you can use the LocalizedStringKey(_ string: String) initialiser:如果您希望该属性被本地化,您可以使用LocalizedStringKey(_ string: String)初始化程序:

Text(LocalizedStringKey(self.type))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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