我有一个可本地化为 2 种语言的应用程序。在 SwiftUI 图表中,我使用 LocalizedStringKey 遇到错误。使用 String 代替 LocalizedStringKey 是可行的,但 x 轴和 y 轴值未本地化。有没有办法本地化这些轴值?我是否必须使用 LocalizedStringKey,如果是的话我该如何制作这个绘图?
我的缩短代码:
import SwiftUI
import Charts
enum PickerQuestions: LocalizedStringKey, CaseIterable { //with String the charts draws but no localization
case Q1 = "first question"
case Q2 = "second question"
case Q3 = "third question"
}
enum PickerCategory: LocalizedStringKey, Codable, CaseIterable { //idem
case picker1 = "not"
case picker2 = "a little"
case picker3 = "medium"
case picker4 = "very"
}
class PickerDataForBarChart: Identifiable {
let id = UUID()
var question: PickerQuestions
var category: PickerCategory
var percentage: Double
init(question: PickerQuestions, category: PickerCategory, percentage: Double) {
self.question = question
self.category = category
self.percentage = percentage
}
}
//stubdata
var chartDataStub: [PickerDataForBarChart] = [
.init(question: .Q1, category: .picker1, percentage: 50),
.init(question: .Q2, category: .picker2, percentage: 75),
.init(question: .Q3, category: .picker1, percentage: 25),
]
//the barchart
Chart(chartDataStub) {spec in
BarMark(
x: .value("Number", spec.percentage),
y: .value("Question", spec.question.rawValue) //error: Initializer 'init(x:y:width:height:stacking:)' requires that 'LocalizedStringKey' conform to 'Plottable'
)
.foregroundStyle(by: .value("Category", spec.category.rawValue)) //error: Instance method 'foregroundStyle(by:)' requires that 'LocalizedStringKey' conform to 'Plottable'
}
.chartForegroundStyleScale( //foreGroundStyle-array and scale-array have to be exactly the same!
domain: [PickerCategory.picker1.rawValue, PickerCategory.picker2.rawValue, PickerCategory.picker3.rawValue, PickerCategory.picker4.rawValue], //error: Referencing instance method 'chartForegroundStyleScale(domain:range:type:)' on 'Array' requires that 'LocalizedStringKey' conform to 'Plottable'
range: [Color.blue, Color.red, Color.yellow, Color.gray]
)
.frame(height: 350)
PS 我通过检查设备语言设置并有条件地为每种语言使用字符串数组来使用解决方法,但必须有更好的方法(我希望)。有人出主意吗?
您可以将枚举更改为原始类型
String
。然后添加一个计算属性,根据“如何在 SwiftUI 中将 LocalizedStringKey 更改为 String”的答案返回原始值的本地化版本。例如:
enum PickerQuestions: String, CaseIterable {
case Q1 = "first question"
case Q2 = "second question"
case Q3 = "third question"
var localized: String {
let localizedKey = String.LocalizationValue(stringLiteral: rawValue)
return String(localized: localizedKey)
}
}
然后,不要将
.rawValue
传递给
BarMark
,而是传递 .localized
:BarMark(
x: .value("Number", spec.percentage),
y: .value("Question", spec.question.localized)
)
.foregroundStyle(by: .value("Category", spec.category.localized))