我对 SwiftUI 很陌生。我正在创建一个选择器,它可以让用户选择他们的体重(以及类似的身高)。如您所知,在美国(和其他一些国家),人们使用英制单位(磅、英尺等),而在大多数其他国家,人们使用公制(公斤、米等)。如何使该选择器轻松准确地适应用户的区域/区域设置?例如,如果用户所在地区使用公制,则显示[40kg, 42.5kg, 45kg, 47.5kg, .... 300kg];如果是英制,则显示 [80lb, 85lb, 90lb, ..., 600lb]
这是我的代码草案,基本上硬编码了英制测量的内容:
import SwiftUI
struct SetMyWeightView: View {
// This works for imperial system. But how I can make it work for both imperial and metric system? For example, if user's region uses metric system, display [40kg, 42.5kg, 45kg, 47.5kg, .... 300kg]; if imperial, display [80lb, 85lb, 90lb, ..., 600lb]
@State private var myWeight: Int?
var body: some View {
Form {
Section {
Picker("", selection: $myWeight) {
// Offer user an option to hide their weight
Text("Hide").tag(nil as Int?)
// Choose from a list [80, 85, 90, ..., 600]
ForEach(Array(stride(from: 80, to: 601, by: 5)), id: \.self) { weight in
Text("\(weight) lb").tag(weight as Int?)
}
}
.pickerStyle(.wheel)
} header: {
Text("Weight")
}
}
}
}
#Preview {
SetMyWeightView()
}
您可以通过使用 Locale.current 类来实现这一点。其中有两个属性(其中之一是在 iOS 16 中引入的,它告诉您设备采用哪种公制系统。代码如下:
struct SetMyWeightView: View {
var isMetric: Bool {
let locale = Locale.current
if #available(iOS 16, *) {
return locale.measurementSystem == .metric
} else {
return locale.usesMetricSystem
}
}
var weightUnit: String {
return isMetric ? "kg" : "lb"
}
var weightRange: ClosedRange<Int> {
return isMetric ? 40...300 : 80...600
}
@State private var myWeight: Int?
var body: some View {
Form {
Section {
Picker("", selection: $myWeight) {
// Offer user an option to hide their weight
Text("Hide").tag(nil as Int?)
ForEach(Array(stride(from: weightRange.lowerBound, through: weightRange.upperBound, by: 5)), id: \.self) { weight in
Text("\(weight) \(weightUnit)").tag(weight as Int?)
}
}
.pickerStyle(.wheel)
} header: {
Text("Weight")
}
}
}
}
尝试一下,让我知道这是否适合您!