您好,我在格式化 TextField 输入时遇到一些问题,因为我希望在每个输入和输出中具有相同的本地格式。在图像上,您可以看到 TextField 内的文本具有不同的格式。
我的简单代码:
struct HomeView: View {
@State var value: Double?
var body: some View {
VStack {
Text("\(value ?? 0)")
.font(.title)
TextField("0.0",
value: $value,
format: .number.precision(.fractionLength(2)))
.border(.red)
.keyboardType(.decimalPad)
}
}
}
有可能统一这种行为吗?
您已经知道如何向
format:
提供 TextField
。您可以对Text
执行相同的操作。
Text(value ?? 0, format: .number.precision(.fractionLength(2)))
您也可以在字符串插值中执行相同的操作:
Text("Some Text \(value ?? 0, format: .number.precision(.fractionLength(2))) Some Text")