看起来Xcode 13.3用格式化程序破坏了TextField。例如,在下面的文本中,应该显示在TextField中输入的值,当使用Xcode 13.2.1 (再次降级为测试)构建时,这个值工作得很好,但是使用Xcode 13.3,TextField不会更新它的绑定值。
struct ContentView: View {
@State var value: Float?
let decimalFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 3
return formatter
}()
var body: some View {
VStack {
TextField("some float", value: $value, formatter: decimalFormatter)
.multilineTextAlignment(.center)
.keyboardType(.decimalPad)
Text("Value: \(value != nil ? String(value!) : "nil")")
}
}
}
发布于 2022-03-22 21:02:25
找到了一个不同的API,它可以实现我期望的选项:*值:格式:提示符:)-6ug7k
TextField("some float", value: $value, format: FloatingPointFormatStyle.number)
虽然这并不能解释为什么它以前使用格式化程序并停止使用Xcode 13.3,但至少这个API似乎是针对可选值的。
将分数位限制在3也是有效的,它只是在编辑过程中不是立即应用,而是在焦点改变之后应用。
TextField("some float", value: $value, format: FloatingPointFormatStyle.number
.precision(NumberFormatStyleConfiguration.Precision.fractionLength(0...3)))
发布于 2022-05-12 00:47:45
使用@harp的回答中的方法更正代码示例。这只适用于iOS 15+。
TextField("some float",
value: $value,
format: .currency(code: "USD"))
.onChange(of: value) { newValue in
print ("value is \(newValue)")
}
format
的另一个例子。这里使用来自FloatingPointFormatStyle上的苹果文档的实例方法之一
TextField("some float",
value: $value,
format: FloatingPointFormatStyle().decimalSeparator(strategy: .automatic))
有关此方法的更多信息,请参见*值:格式:提示:)。
https://stackoverflow.com/questions/71564332
复制相似问题